Bootstrap email validation regular expression - javascript

The following code accepts admin#admin. How can I make it invalid. It should accept admin#admin.com. So basically I need the domain name to make the value accepted.
fields: {
txtEmail: {
validators: {
emailAddress: {
message: 'The email address is not valid'
}
}
}
}

emailAddress: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'The value is not a valid email address'
}

fields: {
email: {
validators: {
notEmpty: {
message: 'Địa chỉ email không được để trống.'
},
regexp: {
regexp: /^[\w,\\"]+([-+.\']\w+)*#(?:(?=[a-z,A-Z])\w+([-.]\w+)*\.\w+([-.]\w+)*$|(?![a-z,A-Z])((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)/,
message: 'This value not valid.'
}
}
},
and in html remove type="email" in input
<label for="email">Email<span style="color: red;"> *</span></label>
<input id="email" class="form-control form-control-lg font-weight-600" name="email" placeholder="Địa chỉ email" required="">

I always use this function, proved to be best so far for me
/*
* Validate Email
* #params element
* #return boolean false || true
*/
var validateEmail = function(element){
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if( !email_regex.test( element ) ) {
return false;
} else{
return true;
}
};
now for using you can do something like this
validateEmail( $('#email_elem').val() )
EDIT: Sorry for not posting answer related to BootstrapValidator
so for bootstrapvalidator do following,
regexp: {
regexp: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i,
message: 'Please enter correct email
}
could you try above regex? & see if it works.
OR try this
fields: {
email: {
validators: {
emailAddress: {
message: 'The value is not a valid email address'
},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'The value is not a valid email address'
}
}
}
}
EDIT: created this working fiddle please check https://jsfiddle.net/yeoman/436rvcut/3/

Related

JQuery validate not implementing 'required' in email field

I've a simple HTML input:
<input id="email" name="email" value="" type="email">
and validate it using JQuery validate:
$('form').validate({
rules: {
email: {
required: 'true',
email: 'true'
}
}
});
The rules are applied, I can see them in $('#email').rules(). However when I later run $('#email').valid() or $('form').valid() the input is marked as valid when empty, but invalid when an invalid email address is entered.
How do I ensure the input is invalid when empty?
Relevant JSfiddle: https://jsfiddle.net/ycypuy86/
I usually set these without quotes?
rules: {
email: {
required: true,
email: true
}
}
remove quotes on your fiddle and it works.

ValidationObj not working

I am trying to validate a form using jquery validation and I keep receiving an error "Uncaught TypeError: Cannot read property 'settings' of undefined".
The error is coming from the jquery-latest.min.js file and my jquery.validate.min.js file. Any suggestions on how to fix this?
Also, when I remove validationObj.form(); block, the error goes away, but then the validation rules are not running.
Here is my HTML:
<div id="contactForm">
<p>Contact Information</p></br>
<div id="contactInfo">
<label>First Name:</label>
<input type="text" name="fName" id="fName"/></br>
<label>Last Name:</label>
<input type="text" name="lName" id="lName"/></br>
<label>Email:</label>
<input type="text" name="email" id="email"/></br>
<label>Phone:</label>
<input type="text" name="phone" id="phone"/></br>
</div></br>
And here is my js:
var validationObj = $("#contactForm").validate
(
{
rules:
{
fName:{required:true},
lName:{required:true},
email:{required:true, email:true},
},//End rules
messages:
{
fName:{equalTo:"Please enter your first name"},
lName:{equalTo:"Please enter your last name"},
email:{minlength:"Please enter a valid email"},
},//End messages
errorPlacement:
function(error, element)
{
error.appendTo( element.next());
}
}//End validationObj
);//End var validationObj
validationObj.form();
$("form").submit
(function(e)
{
if(!validationObj.form())
{
alert("Form Errors");
}
}
);
}
Wrapped it in a form and removed the call before the submit. Working fiddle.
var validationObj = $("#contactForm").validate({
rules: {
fName: {
required: true
},
lName: {
required: true
},
email: {
required: true,
email: true
},
}, //End rules
messages: {
fName: {
equalTo: "Please enter your first name"
},
lName: {
equalTo: "Please enter your last name"
},
email: {
minlength: "Please enter a valid email"
},
}, //End messages
errorPlacement: function(error, element) {
error.appendTo(element.next());
}
} //End validationObj
); //End var validationObj
$("#contactForm").submit(function(e) {
if (!validationObj.form()) {
alert("Form Errors");
} else {
alert("Form Valid");
}
});

How to trigger jquery validation on form submit rather than on blur

I am using Jquery validation plugin to validate, I am trying to validate all fields on click of submit button.
But if you see in fiddle by typing wrong email format and if you move to password that next input field it gives message saying "Please enter a valid email address", which I dont want.
I want all fields to validate on click of submit button till then submit button should be disabled when all fields are valid then allow user to click and validate once again to check fields.
is it possible to invoke validaion plugin on submit?
Here is what I tried so far
Html code
<form action="" method="post" id="register-form" >
<div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>
my js code
$(function() {
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
});
Try this..
$(function() {
onfocusout: false,
onkeyup: false,
onclick: false
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
},
errorPlacement: function(error,element) {
return true;
},
invalidHandler: function(event, validator) {
alert(validator.valid());
//if(validator.valid()) show your modal then use validator.errors() to show custom errors
}
});
});
This simple validation might work for you. Please have a look.
$('tab').addClass('inactive);
$('input[type="submit"]').click(function(){
//Onclick get all the input value
var firstname = $("#firstname").val(),
lastname = $("#firstname").val(),
email = $("#email").val(),
psw = $("#password").val(),
regx = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
//If anything is invallid
if(firstname == "" || lastname == "" || email == "" || !regx.text(email) || psw == ""){
if(firstname == ""){ //if firstname is blank
alert("Please enter your first name");
}
if(lastname == ""){ //if lastname is blank
alert("Please enter your last name");
}
if(email == ""){ //if email is blank
alert("Please enter email id");
}
if(!regx.text(email)){ //if email is not in proper format
alert("Please enter valid email id");
}
if(psw == ""){ //if password is blank
alert("Please enter password");
}
return false; //form will not submit, it will return false
}else{
$('.tab').addClass('active').removeClass('inactive'); //if for is valid, add/remove class to the element
}
});

Validate form fields using ajax

I do have a jquery code to validate my form but unfornutately it is not that accurate. I would like to validate the fields thoroughly like only to accept numbers on phone field and only a valid email address on email field.
Also I would like to show the error ( or just add a red border one field ) as soon as the user types/inputs a value without clicking submit button, so it looks like a real time checker.
Can anyone derive my script, I am really not confident about this. Also derive my php code if u think it is wrong. Would love to learn how to use session also so user can only submit once every session.
Code:
<head>
<script>
$(function () {
$('.cbf').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
if ( name == "" ) {
alert('Please provide valid name');
$('#name').addClass('error');
}
else if ( phone == "" ) {
alert('Please provide a valid phone number');
$('#phone').addClass('error');
$('#name').removeClass('error');
}
else if ( email == "" ) {
alert('Please provide a valid email');
$('#email').addClass('error');
$('#phone').removeClass('error');
}
else {
$.ajax({
type: 'post',
url: 'index.php',
data: $('.cbf').serialize(),
data: "name="+ name +"& phone="+ phone +"& email="+ email,
success: function () {
alert('We will contact you shortly! Thanks!');
},
complete:function(){
$('.cbf').each(function(){
this.reset(); //Here form fields will be cleared.
});
}
});
$('#email').removeClass('error');
}
});
});
</script>
</head>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" class="cbf">
<fieldset>
<input type="text" id="name" name="name" value="" placeholder="Name">
<input type="text" id="phone" name="phone" value="" placeholder="Phone">
<input type="email" id="email" name="email" value="" placeholder="Email Address">
<input type="submit" id="submit" name="submit" value="Get Call Back">
</fieldset>
</form>
<?php
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION['posted'] = true;
$to = "myemail#gmail.com";
$subject = "Someone wants a Call Back!";
// data the visitor provided
//$name_field = $_POST['name'];
//$phone_field = $_POST['phone'];
//$email_field = $_POST['email'];
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_INT);
//constructing the message
$body = " From: $name_field\n\n Phone: $phone_field\n\n E-mail: $email_field\n\n";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
Try this code :
$("#signupform").validate({
rules: {
email: {
required: true,
email: true
},
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
}
},
messages: {
email: {
required: "Please enter a valid email address.",
email: "Invalid Email Address."
},
mobile: {
required: "Please provide a mobile number.",
minlength: "Your mobile number must be 10 characters long.",
maxlength: "Your mobile number must be 10 characters long.",
number: "Please Enter number only."
}
}
});
Its better to validate on both server side and client side. Client side validate then display the error to user. On server side, you need to validate again, just because your JS code can be changed by malicious user.
A simple example with phone.
//client side
var phone = $('#phone').val();
//validate
if(/^\d+$/.test(phone) === false){ //not number
alert('Your phone number is not valid');
}
//on server side
$phone = $_POST['phone'];
if(is_numeric($phone)){
insert $phone into database.
}
Another way is to use HTML5 and new tags like : "email" and "tel" (tel is not supported for the moment) :
<input type="tel" name="phone" required>
and for email :
<input type="email" name="email" required>
Even the solution you choose, you have to do a control on the server side in Php for your case.
It's not the solution but in the futur, I think we should use these tags.
More informations : http://www.w3schools.com/html/html5_form_input_types.asp
Here is a simple jQuery validation:
The form:
<form id="myform">
email<input type="text" name="field1" />
<br/>
password<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
The validation part
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
http://jsfiddle.net/VuPPy/

jQuery validation of two fields len().

Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/

Categories