I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)
Related
I have done a javascript form validation using the following code.I'm not sure whether it is the correct way of validating form.
const signup=()=>{
let name=document.querySelector("#u_name").value;
let email=document.querySelector("#email_id").value;
let password=document.querySelector("#pwd").value;
let confirmPassword=document.querySelector("#confirm_pwd").value;
let i=0;
if((name==""||email=="")||(password==""||confirmPassword==""))
{
document.querySelector("#empty-field").innerHTML="*Fill all required fields";
i++;
}
else
{
if(name.length<3)
{
document.querySelector("#u_name").style.borderColor="red";
document.querySelector("#user-errmsg").innerHTML="*Enter valid user name";
i++;
}
else
{
document.querySelector("#u_name").style.borderColor="#ced4da";
document.querySelector("#user-errmsg").innerHTML="";
i;
}
if(email.length<6)
{
document.querySelector("#email_id").style.borderColor="red";
document.querySelector("#email-errmsg").innerHTML="*Enter valid email id";
i++;
}
else
{
document.querySelector("#email_id").style.borderColor="#ced4da";
document.querySelector("#email-errmsg").innerHTML="";
i;
}
if(password.length<6 && confirmPassword.length<6)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length<6 && confirmPassword.length>=6)
{
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length>=6 && confirmPassword.length>=6)
{
if(password!= confirmPassword)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
else
{
document.querySelector("#pwd").style.borderColor="#ced4da";
document.querySelector("#confirm_pwd").style.borderColor="#ced4da";
document.querySelector("#pwd-errmsg").innerHTML="";
i;
}
}
else
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
document.querySelector("#empty-field").innerHTML="";
}
if(i==0)
return true;
else
return false
}
Is it a good practice to write too many if else condition? If not, how can I rewrite it?
//ignore
Looks like stackoverflow doesn't allow posting this question with less details :/ So I have to add some more it seems.
Your concern about using too many if/else statements during the scope of a single method is a valid one. It is not wrong, but makes the code hard to read/understand and difficult to debug/troubleshoot if something goes wrong. Here are some advices to refactor this method:
It seems that it isn't doing a signup. You're validating input data so I would recommend to rename it to validate or something similar.
Method is doing too much. It's querying for the data, it's performing validations and also rendering messages and adapting styles. I advice to divide and conquer. Make this method just a validation one.
Create small functions that performs a single validation. As an example validateEmailAddress() or validatePassword(). Once you start moving pieces around, you will have less if/elseif statements.
There are more things you can do but the key is on decoupling responsibilities. If you try that I believe your if/elseif amount will decrease.
There is another strategy that I use all the time to remove if/else nesting levels which is commonly called as early return.
Your code would benefit from extracting everything into functions:
const get = selector => document.querySelector(selector);
const checker = (check, msg) => (el, error) => {
if(check(get(el).value)){
get(el).style.color = "green";
get(error).innerHTML = "";
return true;
} else {
get(el).style.color = "red";
get(error).innerHTML = msg;
}
};
const minLength = length => checker(
v => v.length >= length,
`Too short! You need at least ${length} chars`
);
const maxLength = length => checker(
v => v.length <= length,
`Too long! You need less than ${length} chars`
);
const equal = (a, b, err) => checker(v => v === get(b).value, "They must be equal")(a, err);
Seems quite long right? But now you can do:
return (
minLength(6)("#u_name", "#user-errmsg") &&
maxLength(12)("#u_name", "#user-errmsg") &&
minLength(6)("#email_id", "#email-errmsg") &&
equal("#confirm_pwd", "#pwd", "#pwd-errmsg")
)
use jquery plugin https://jqueryvalidation.org/
Below is the example to use:
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "myform"
$("form[name='myform']").validate({
// Specify validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify 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 8 characters long"
},
email: "Please enter a valid email"
},
submitHandler: function(form) {
form.submit();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div>
<h2>Sign Up</h2>
<form action="" name="myform">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="Robert" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Smith" />
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="name#company.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="" />
<button type="submit">Submit</button>
</form>
</div>
CSS to highlight error
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
You don't need any javascript validation or extra library, just use all the attributes that is needed on the fields and correct type. use "constraint validation". Only thing you need to check is if the password match (showing you how below)
Study the input attributes here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
function validatePassword(){
const pwd1 = document.getElementById("pwd")
const pwd2 = document.getElementById("confirm_pwd")
pwd1.setCustomValidity(pwd1.value !== pwd2.value
? "Passwords Don't Match"
: ""
)
}
document.getElementById("pwd").oninput = validatePassword
document.getElementById("confirm_pwd").oninput = validatePassword
input:not([type=submit]):valid {
border: 1px solid lime;
}
<form class="" action="index.html" method="post">
<br>name<br>
<input name="" required type="text" autocomplete="name" minlength="3" id="u_name">
<br>email<br>
<input name="" required type="email" autocomplete="email" id="email_id">
<br>pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="pwd">
<br>repeat pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="confirm_pwd">
<br><input type="submit">
</form>
Personally I feel very tired off repeating my email and/or password. If i get it wrong i will do it over again or press that "forgot your password" link. I can see my email address and with the help of autocomplete it's a lower risk i get my email wrong. You don't need that b/c every other website dose it. if that is out of the way you don't need any javascript at all...
I have the following html form:
<form class="center" id="myform">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
<input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
</div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" id="postmelater" value="send" disabled/>
</form>
And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:
$(document).ready(function () {
$('#myform').validate({// initialize the plugin
errorElement: 'div',
rules: {
email: {
required: true,
email: true
},
slogan: {
required: true,
minlength: 2
},
terms: {
required: true,
maxlength: 2
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
});
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
});
There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!
Here depends on functionality of validation plugin, when it reacts, but likely you can try to add onclick to buttons which sets some hidden variable, indicating which button was pushed. Like this:
<input type="submit" id="sendfeedback" onclick="this.form.clickedbtn.value=1" value="now" disabled/>
<input type="submit" id="postmelater" value="send" onclick="this.form.clickedbtn.value=2" disabled/>
and also add hidden input to the form like this
<input type="hidden" id="clickedbtn" name="clickedbtn">
Than in the handler add
var clickedbtn = $("#textarea").val();
...
clickedbtn: clickedbtn,
so form will look like this:
<form class="center" id="myform">
<input type="hidden" id="clickedbtn" name="clickedbtn">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
I accept terms
</p>
<input type="submit" id="sendfeedback" value="now" onclick="this.form.clickedbtn.value=1" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" onclick="this.form.clickedbtn.value=2" id="postmelater" value="send" disabled/>
</form>
And handler will look like this:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
var clickedbtn = $("#textarea").val();
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
clickedbtn: clickedbtn,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
After that in php script you can check
if ($_POST["clickedbtn"]==1) {
send now code
} else {
other code
}
Change
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
to
$('#myform').find('input, textarea').on('change', function () {
var sendfeedbackbtn = $('#sendfeedback');
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
if ($('#myform').valid()) {
sendfeedbackbtn.removeAttr('disabled');
datepicker.removeAttr('readonly');
if (isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
}
} else {
datepicker.attr('readonly', 'readonly');
sendfeedbackbtn.attr('disabled', 'disabled');
postmelaterbtn.attr('disabled', 'disabled');
}
});
So it enables the sendfeedback and the timestamp input area. And if not valid, all button and timestamp area will be disabled.
Then add
$('#myform').find('#datetimepicker').on('change', function () {
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
// Need to implement isTimeValid method.
if ($('#myform').valid() && isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
} else {
postmelaterbtn.attr('disabled', 'disabled');
}
});
So when the timestamp area is changed, check if its valid (need implement isTimeValid), and decide whether to make postmelater able to clicked or not.
And your submit handler should be:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
// Decide to send a timestamp data or not.
var timestamp = $('#datetimepicker').attr('readonly') ? null : $('#datetimepicker').val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
// So this value will be null or whatever your input
timestamp: timestamp
},
success: function(response)
{
alert(response);
}
});
}
And you can decide PHP side's behavior on whether the given timestamp is a null value or not.
As you give all these inputs an id, I directly use its id selector to get them, but you can still change to other selector at wish.
You could use js/php to set the default value of your date field to be current date. That way you would only need one submit button:
<input type="date" value="<?php echo date("Y-m-d")?>">
or
<input type="date" id="datefield">
<script>
document.getElementById("datefield").value = new Date().getFullYear()+"-"+("0"+(new Date().getMonth()+1)).slice(-2)+"-"+("0" + new Date().getDate()).slice(-2);
</script>
But if you absolutely want to have two buttons, you could do:
<input type="button" onClick="firstButton()">
<input type="button" onClick="secondButton()">
and
function firstButton(){
//do what you need to
document.getElementsByTagName("form")[0].submit();
}
...and same for button two.
I have a form set up with the jQuery Validation plugin.
see here: http://jsfiddle.net/9q865xof/
And I have this (non-jquery) javascript function from how my form was validated before adding the plugin.
function busregform(form, password) {
// new input for hashed password
var p = document.createElement("input");
// create element
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// clear plaintext password
password.value = "";
// submit the form
form.submit();
return true;
}
With the hex_sha512() function in its own file too.
The idea here is to post the password from the form through busregform() to create a hashed password to then post for my PHP script to process.
I have tried adding this to my validation jquery code:
submitHandler: function(){
var pw = $("#pass").val();
var form = $("#business-reg-form");
busregform(form,pw);
}
With no luck... Not sure what to do now. I'm thinking I should use ajax?
How can I call busregform() when the plugin-validated form is submitted?
The busregform method is expecting a dom element reference for form so you need
$('#business-reg-form').validate({
rules: {
address: {
required: true,
minlength: 6
},
email: {
required: true,
email: true,
minlength: 6
},
company: {
required: true
},
pass: {
required: true,
minlength: 6
},
confirmpw: {
required: true,
minlength: 6,
equalTo: "#pass"
}
},
submitHandler: function() {
var pw = $("#pass");
var form = $("#business-reg-form");
//pass the dom element reference
busregform(form[0], pw[0]);
return false;
}
});
function busregform(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
return true;
}
if (!window.hex_sha512) {
//stub method
window.hex_sha512 = function(value) {
return 'hex_sha512-' + value;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<form method="post" name="business_regform" id="business-reg-form" action="">
<p>
<input type="text" name="company" id="company" placeholder="company name" required />
</p>
<p>
<input type="text" name="address" id="address" placeholder="address" required />
</p>
<p>
<input type="text" name="email" id="email" placeholder="email" required />
</p>
<p>
<input type="text" name="pass" id="pass" placeholder="password" required />
</p>
<p>
<input type="text" name="confirmpw" id="confirmpw" placeholder="confirm password" required />
</p>
<p>
<input type="submit" class="btn" id="business-reg-submit" value="submit" />
</p>
</form>
Demo: Fiddle - You can inspect the request using the network tab to see the hashed password
working on php project want to do validation at once only at all fields of registration form.
fields
name
address
mobile
all above fields are mandatory so can i write only one function of validation
function validateForm()
{
if (document.myForm.name.value == "")
{
alert("Please enter the name");
document.myForm.name.focus();
return false;
}
if (document.myForm.address.value == "")
{
alert("Please enter the address");
document.myForm.address.focus();
return false;
}
...
}
instead of this how can i write only one function code so that i do not need to check all textbox values separately .
If you add Ids to your input fields...
<input type="text" name="name" id="name"/>
<input type="text" name="address" id="address"/>
<input type="text" name="mobile" id="mobile"/>
You can then do something like...
var Fields = [['name', 'your name'],
['mobile', 'your mobile number'],
['address', 'your address']]
for(x=0; x<Fields.length; x++) {
if(document.getElementById(Field[x][0]).value == '') {
alert('Please enter ' + Field[x][1]);
return false;
}
}
Iam not understanding to do validation for the 'FullName' field..
Below are the validations required for the 'FullName' field:
only letters a to z (lower case), "-" (dash or hyphen) and " "
(space) are allowed,
the "-" (dash) AND " " (space) letters MUST be entered,
the "-" or the " " letter must not be either the first or the last
letter entered,
"-" must not be the immediate neighbour or adjacent (before or after)
to a " ",
"-" or " " must not be the immediate neighbour (adjacent) to itself.
I knew I can do in this way:
$('#fullName').blur(function(){
var input = $('#fullName').val();
if( !/[^a-z0-9 -]/.test(input) &&
/ /.test(input) && /-/.test(input) &&
!/^[ |-]|[ |-]$/.test(input) &&
!/ -|- |--| /.test(input))
{
$('.error').remove();
}
else{
$('#fullName')
.after('<span class="error">Your Name should be entered like: "blahblah" </span>');
}
});
BUT I am not understanding how to insert above regex code into here:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>
<script>
$(document).ready(function(){
$("#fullname").focus();
$("#fullname").addMethod("alphanumeric", function(value, element) {
return ! $("#fullname").methods.required(value, element) || /^[a-zA-Z0-9_]+$/i.test(value);
} , "Letters, numbers or underscores only please");
$("#ourform").validate({
onfocusout: function(element) { $(element).valid(); } ,
rules: {
fullname : {
required: true,
maxlength: 14,
alphanumeric : false
},
email: {
required: true,
email: true
}
},
messages: {
fullname : {
required: "Please specify your Full Name",
maxlength: "Please enter only upto 14 characters",
alphanumeric : "do not enter alphanumeric"
},
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name#domain.com"
}
}
});
});
</script>
<style>
.error {color: red;}
</style>
</head>
<body>
<form id="ourform" method="get" action="">
<fieldset>
<p>
<label for="fullname">Full Name</label>
<em>*</em><input id="fullname" name="fullname" size="25" class="required" maxlength="14" />
</p>
<p>
<label for="email">Email</label>
<em>*</em><input id="email" name="email" size="25" class="required email" />
</p>
</fieldset>
</form>
</body>
</html>
EDITED:
- FullName (both first and family name - use ONE field for both),
You have two questions here:
How to validate the full name per your rules.
How to add custom jQuery validator validation rules.
How to add custom jQuery validator validation rules
Here is an example of validating the field has the value "Mark" for fullname:
$(document).ready(function() {
var fullname_invalid = function(value) {
return value === "Mark";
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_invalid(value);
}, 'Your Name should be entered like: "Mark"');
$('#signup').validate({
rules: {
fullname: {
required: true,
custom_fullname: true
}
}
});
$('#signup').on('submit', function(event) {
event.preventDefault();
});
});
HTML:
<form id="signup" action="/action">
<input name="fullname" type="text" />
<input type="submit">
</form>
Demo: jsfiddle
Reference: jQuery Validate Plugin - How to create a simple, custom rule?
How to validate the full name per your rules
$(document).ready(function() {
var validCharactersRegex = new RegExp(/^[a-zA-Z0-9 -]+$/);
var doesNotStartWithDashOrSpace = new RegExp(/^[^ -]/);
var fullname_invalid = function(value) {
return validCharactersRegex.test(value) && doesNotStartWithDashOrSpace.test(value) && value.indexOf(' ') == -1 && value.indexOf('--') == -1 && value.indexOf(' -') == -1 && value.indexOf('- ') == -1;
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_invalid(value);
}, 'Your Name should be entered like: "blahblah"');
$('#signup').validate({
rules: {
fullname: {
required: true,
custom_fullname: true
}
}
});
$('#signup').on('submit', function(event) {
event.preventDefault();
});
});
Demo: jsfiddle