Check all conditions in form using jquery - javascript

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<h1>USER REGISTRATION</h1>
<br>
<form class="for" name="ureg" method="post" action="">
<fieldset style="margin-right: 900px">
<legend>Registration Form</legend>
<pre>
Name <input class="name" type="text"><span id="errmsg5"></span></input><br><br>
User Name <input class="uname" type="text"><span id="errmsg6"></span></input><br><br>
Password <input class="pass" type="password" name="pass"><span id="errmsg7"></span></input><br><br>
Confirm Password <input class="cpass" type="password" name="cpass"><span id="errmsg1"></span></input><br><br>
Email <input type="email"></input><br><br>
Gender <input type="radio" name="gender" value="male">Male</input><input type="radio" name="gender" value="female">Female</input><br><br>
Country <select name="country" style="width: 175px;">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="sri lanka">Sri Lanka</option>
<option value="china">China</option>
<option value="china">Japan</option>
<option value="china">Bangladesh</option>
</select><br><br>
Mobile <input class="mob" type="number"><span id="errmsg3"></span></input><br><br>
Age <input class="age" type="number" name="age"><span id="errmsg2"></span></input><br><br>
D.O.B <input type="date"></input><br><br>
Address
<textarea rows="4" cols="50" name="address"></textarea><br><br>
Pincode <input class="pin" type="number"><span id="errmsg4"></span></input><br><br>
<input id="submit" type="submit" value="SUBMIT"> <input id="reset" type="submit" value="RESET">
</pre>
</fieldset>
</form>
<script type="text/javascript">
$(function () {
$(".cpass").change(function () {
var password = $(".pass").val();
var confirmPassword = $(".cpass").val();
if (password != confirmPassword)
{
$("#errmsg1").text(" Password does not match");
return false;
}
else
{
$("#errmsg1").text("");
return true;
}
});
$(".age").change(function () {
$("#errmsg2").text(" ");
var n = $(".age").val();
if (n < 18) {
$("#errmsg2").text( " Age should be > 18");
return false;
}
return true;
});
$(".mob").change(function () {
$("#errmsg3").text( " ");
var mobile = $(".mob").val();
if (mobile.length != 10) {
$("#errmsg3").text( " Not a valid number");
return false;
}
return true;
});
$(".pin").change(function () {
$("#errmsg4").text( " ");
var mobile = $(".pin").val();
if (mobile.length != 6) {
$("#errmsg4").text( " Not a Valid Pincode");
return false;
}
return true;
});
$(".name").change(function () {
$("#errmsg5").text( " ");
var name = $(".name").val();
var pattern = new RegExp("^[A-z]+$");
if (!pattern.test(name)) {
$("#errmsg5").text( " Name should contain only letters");
return false;
}
return true;
});
$(".uname").change(function () {
$("#errmsg6").text( " ");
var uname = $(".uname").val();
var pattern = new RegExp("^[A-z0-9]+$");
if (!pattern.test(uname)) {
$("#errmsg6").text( " User Name should contain only numbers and alphabets");
return false;
}
return true;
});
$(".pass").change(function () {
$("#errmsg7").text(" ");
var pass = $(".pass").val();
if(pass.length>8)
{
var caps = /[A-Z]/.test(pass);
var small = /[a-z]/.test(pass);
var num= /[0-9]/.test(pass);
var sp=/\W|_/.test(pass);
if(caps&&small&&num&&sp)
{
$("#errmsg7").text("");
return true;
}
else
{
$("#errmsg7").text("Password should be of minimum 8 characters and contain atleast 1 upper case, 1 lower case, 1 digit and 1 special characters");
return false;
}
}
else
{
$("#errmsg7").text("Password should be of minimum 8 characters and contain atleast 1 upper case, 1 lower case, 1 digit and 1 special characters");
return false;
}
});
});
</script>
</body>
</html>
this my code for validating the form. Once the SUBMIT is pressed i want to check the values one more time. or alternatively the the submit would work only when all the conditions are true. is there any way to do it?

You can target the form and check for the 'submit' event, then return false if the values aren't right. Alternatively, you could preventDefault on the event with e.preventDefault(); and submit the form with AJAX.
EDIT: Here's the short version of what I generally do as a first-pass for form validation. Note that this is the absolute least you should be doing. Users can simply remove the required attribute, and get by your first-pass validation, so you should always check for the absolutely required fields in addition, as well as check on the server-side after sanitizing the input. (As in, remove disallowed chars then check for proper data.)
$('form.validate').on('submit', function(e, el) {
var inputs = $(this).find('input[required]'),
empty = $(inputs).map(function(e, el) {
if (el.value === '') {
return el;
}
});
if (empty.length > 0) {
return false;
}
})

Related

Using the outcome of a function in another function [duplicate]

This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed last year.
I have created 3 functions to cilentside validate a form for its name, email, and website, I would like to create a 4th function that checks if the outcome of the 3 first functions is true, we submit the form, if the outcome of any of them is false, the form doesn't get submitted. Below is my attempt for the JavaScript.
The purpose of this question is to learn how to use a 4th function to check the other 3 functions returns.
//validating name, email, website:
function nameValidation() {
var valid = true;
var name = document.getElementById("name1").value;
var validname = /^[a-zA-Z\s]*$/;
if (name == "") {
document.getElementById("errorMsg2").innerHTML = "* Name is required";
valid = false;
} else if (name.match(validname)) {
valid = true;
} else {
document.getElementById("errorMsg2").innerHTML = "* Only letters and white spaces allowed";
valid = false;
}
return valid;
}
function emailValidation() {
var valid = true;
var validEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var email = document.getElementById("email1").value;
if (email == "") {
document.getElementById("errorMsg3").innerHTML = "* Email is required";
valid = false;
} else if (email.match(validEmail)) {
valid = true;
} else {
document.getElementById("errorMsg3").innerHTML = "*Please enter a valid email.";
valid = false;
}
return valid;
}
function websiteValidation() {
var valid = true;
var validWebsite = /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i;
var website = document.getElementById("website1").value;
if (website == "" || website.match(validWebsite)) {
valid = true;
} else {
document.getElementById("errorMsg4").innerHTML = "* Website is required";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit() {
if (nameValidation() == true && emailValidation() == true && websiteValidation() == true) {
return true;
} else {
return false;
}
}
document.getElementById("submit").addEventListener("click", () => {
console.log("Final result:", formSubmit());
});
<div>
<div id="errorMsg2"></div>
<input type="text" id="name1" />
</div>
<div>
<div id="errorMsg3"></div>
<input type="text" id="email1" />
</div>
<div>
<div id="errorMsg4"></div>
<input type="text" id="website1" />
</div>
<div>
<input type="submit" id="submit" />
</div>
Delete all of the JavaScript. This is the only HTML you need:
<input type="text" id="name1" pattern="[a-zA-Z\s]+" title="Letters and spaces only" required />
<input type="email" id="email1" required />
<input type="url" id="website1" required />
<input type="submit" id="submit" />
HTML5 Form validation has been around for a very long time at this point.

How to validate textbox to a specified pattern

I have below code that is working fine, but I want to validate textbox TBMonday to force users to enter in the specified pattern. How can I do this with Javascript (Please I don't want to use input type='time')
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" pattern="(2[0-4]|1[0-9]|[1-
9])\:(5[0-9]|4[0-9]|3[0-9]|2[0-9]|1[0-9]|[0-9])-(2[0-4]|1[0-9]|[1-9])\:(5[0-9]|4[0-9]|3[0-
9]|2[0-9]|1[0-9]|[0-9])" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value = document.getElementById('TBMonday').value;
}
</script>
Here is how I finally write my code and it work for me.
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" required
onblur="validateMon();" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function validateMon(){
var phoneNumber = document.getElementById('TBMonday').value;
var phoneRGEX = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5]
[0-9]$/;
var phoneResult = phoneRGEX.test(phoneNumber);
if(phoneResult == false)
{
document.getElementById('TBMonday').value = '';
document.getElementById('TBMonday2').value = '';
alert('Please enter TimeBelt in "HH:MM-HH:MM" format');
return false;
}
return true;
}
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value
document.getElementById('TBMonday').value;
}
</script>

JavaScript only validating the first field

So basically I'm trying to create a list of input boxes which need to each be validated before they can be submit. I'm a very basic beginner at JavaScript and HTML and would appreciate any input as only the first form is being validated. As long as there is alphabetic characters in Forename it will submit.
<p><b> Forename: </b></p>
<input type="text" size="32" name="frmForename" placeholder="Dylan">
<p><b> Surname: </b></p>
<input type="text" size="32" name="frmSurname" placeholder="Owen">
<p><b> Gender: </b></p>
<input type="radio" name="frmGender" value="male"> Male
<input type="radio" name="frmGender" value="female"> Female
<p><b> Date of Birth:</b><p>
<input type ="text" size="32" name="frmDateOfBirth" placeholder="DD/MM/YYYY">
<p><b> Age: </b></p>
<input type ="text" size="32" name="frmAge" min="12" max="150" placeholder="Enter Your Age">
<p><b> Course: </b></p> <select name="frmCourse" id="frmCourse">
<option value="select">Select Your Course</option>
<option value="databases">Databases</option>
<option value="websites">Websites</option>
<option value="networks">Networks</option>
</select>
<p><input type="submit" value="Enter Details" onclick=" return checkForm(); checkForm2();">
<input type="reset" value="Clear Form" onclick="return confirm_reset();">
<button onclick="goBack()">Back</button> </p>
<font size="3" color="red">All forms <u>must</u> be complete.</font>
<p><b> Date Registered: </b></p>
<input type="text" size="55" id="dateReg" readonly/>
</form>
</body>
The JavaScript
<script language="javascript" type="text/javascript">
document.bgColor="LightSteelBlue";
</script>
<script type="text/javascript">
function checkForm(form)
{
//****FORENAME****
// VALIDATE: No Characters
if(form.frmForename.value == "") {
alert("Error: Enter your forename.");
form.frmForename.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[A-Za-z]+$/;
// VALIDATE: Does the entered text match the expression above?
if(!re.test(form.frmForename.value)) {
alert("Error: Cannot use numerical characters.");
form.frmForename.focus();
return false;
}
// validation was successful
return true;
}
</script>
<script>
function checkForm2(form)
//****SURNAME****
if(form.frmSurname.value == "") {
alert("Error: Enter your surname.");
form.frmSurname.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[A-Za-z]+$/;
// VALIDATE: Does the entered text match the expression above?
if(!re.test(form.frmSurname.value)) {
alert("Error: Cannot use numerical characters.");
form.frmSurname.focus();
return false;
}
// validation was successful
return true;
}
</script>
<script>
function getDate() {
document.getElementById('dateReg').value= Date();
}
</script>
<script>
function confirm_reset() {
return confirm("Are you sure?");
}
</script>
<script>
function goBack() {
return confirm("Are you sure?");
window.history.back();
}
</script>
<script>
if(form.frmDateOfBirth.value == "") {
alert("Error: Date Of Birth is empty!");
form.frmDateOfBirth.focus();
return false;
}
re = /^(\d{1,2})/(\d{1,2})/(\d{4})$/;
if(form.frmDateOfBirth.value != '') {
if(regs = form.frmDateOfBirth.value.match(re)) {
if(regs[1] < 1 || regs[1] > 31) {
alert("Invalid value for day: " + regs[1]);
form.frmDateOfBirth.focus();
return false;
}
if(regs[2] < 1 || regs[2] > 12) {
alert("Invalid value for month: " + regs[2]);
form.frmDateOfBirth.focus();
return false;
}
if(regs[3] < 1913 || regs[3] > (new Date()).getFullYear()) {
alert("Invalid value for Date Of Birth: " + regs[3] + " - must be between 1913 and " + (new Date()).getFullYear());
form.frmDateOfBirth.focus();
return false;
}
} else {
alert("Invalid date format: " + form.frmDateOfBirth.value);
form.frmDateOfBirth.focus();
return false;
}
}
</script>
<script>
function validateCourse() {
var x = document.forms["frmCourse"]["frmCourse"].value;
if (x == "select") {
alert("Please select a course.");
return false;
}
}
</script>
This line:
onclick=" return checkForm(); checkForm2();
means that if checkForm returns false (which it does when form.frmForename.value == ""), then the false is used with the return in return checkForm() and the click event is cancelled, so the form does not submit. Then checkForm2() is called, but by then the button click has already been cancelled.
Also, there is no need to separate each function into its own <script> element. You should also be working with the form.submit event, rather than the button.click event and you should not be using inline event handlers (on...), but rather with standard element.addEventListener().

Validating group of radio buttons

function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
for(var i=0; i<form.elements.length; i++)
{
if(form.elements[i].checked)
{
valid = true;
}
else
{
alert("No option selected!");
valid = false;
}
}
return valid;
};
This is my JavaScript function to validate group of radio buttons to check if atleast one of them is selected. And, the one below is my form.
<form name="myForm" font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b"/><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" id="r1" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract" id="r2" /><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply" id="r3" /><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" id="r4" /><br/>
<input type="submit" value="Submit" />
</form>
When i give input and no radio button is selected it should alert the user, but its not happening. Can someone guide where I've gone wrong? And help me out with this? I know there might be lot of duplicates, but I've tried them all to no avail. When i click submit without selecting the radio button it gives me a blank page. Any help is appreciated. Thanks.
Try this, Check the demo here Fiddle
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
var ele = document.getElementsByName("option");
var flag=0;
for(var i=0; i<ele.length; i++)
{
if(ele[i].checked)
{
flag=1;
break;
}
}
if(flag == 0)
{
alert("No option selected!");
valid = false;
}
return valid;
};

validation of input text field in html using javascript

<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.

Categories

Resources