I want to login with either mobile number or email address. My php code is working properly. And now i want to validate login form with jQuery for validate plugin. I have tried for long, but unable to get solution for this. How can I validate input textbox for only email or either mobile number validation?
My jQuery Script:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
email: {
required: true
},
password: {
required: true
}
},
messages: {
email: {
required: "Email or Mobile number is required"
},
password: {
required: "specify password"
}
}
});
});
HTML code:
<div id="bar">
<div id="container">
<!-- Login Starts Here -->
<div id="loginContainer">
<a href="#" id="loginButton"><span>Login</span><em></em></a>
<div style="clear:both"></div>
<div id="loginBox">
<form id="loginForm">
<fieldset id="body">
<fieldset>
<label>Email or Mobile</label>
<input type="text" name="email" id="email" class="required"/>
</fieldset>
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
<input type="submit" id="login" value="Sign in" />
</fieldset>
<span><a href="#">Forgot your password?</a></span>
</form>
</div>
</div>
<!-- Login Ends Here -->
</div>
If in textbox I write email it I validating properly, but when I type mobile number, the error message is displaying.
The plugin allows you to create your own validation rule using the .addMethod()
function, so you can use regular expressions to test the value of the input...
$.validator.addMethod("myusername", function(value,element) {
return this.optional(element) ||
/^[0-9]{10}$/.test(value) ||
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
}, "Username format incorrect.");
And then, apply it...
$("#loginForm").validate({
rules: {
email: {
required: true,
myusername: true
},
password: {
required: true
}
},
messages: {
email: {
required: "Username is required"
},
password: {
required: "specify password"
}
}
});
For the email I've copied the same validation that the plugin uses in its email
rule (use another one if you prefer). For the cellphone, I'm just checking that it has ten numbers wihout spaces, but you can adapt it to the cellphone format you want to allow.