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().
Related
please check the code
function validate() {
var name = document.getElementById("name");
var pwd = document.getElementById("pwd");
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name === null || name === "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
There's a much easier way to do what you are trying to do. You can use the native properties of form to your advantage:
<form>
Username: <input type="text" minlength="2" required>
<br> Password: <input type="password" minlength="6" required>
<br>
<button type="submit">Submit</button>
</form>
HTML elements should be before javascript, like this:
<!DOCTYPE html>
<html>
<body>
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</body>
</html>
You haven't provided the full code, so we can't really help you. As far as i can see you didn't make the alert for succesful validation.
You need to get the value, so you need to add .value to the getElement functions.
When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>
<!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;
}
})
i have a text box or input to save Phone number, i want that Users Can Only be able to Enter 11 Numbers and Just can accept Numbers Not Characters.
how Check and show message.
how this is possible in client side Like JavaScript And then Sending To Server Side.
my code that it`s Incorrect:
<script language="JavaScript" type="text/javascript">
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
and in submit section:
<input type=submit border=0 value=" " Onclick=code(getElementById("Phone").value) />
Thanks
you should use return false after alert in validate condition, try this code
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
}
UPDATE
If you want to accept only 11 number then try with RegEx
function code(input){
if(input.match(/^[0-9]{11}$/)){
return true;
}
alert("Enter a Valid Phone Number");
return false;
}
submit button change Onclick to onClick with quote and use document.getElementById("Phone").value instead of getElementById("Phone").value
<input type=submit border=0 value=" "
onClick='return code(document.getElementById("Phone").value)' />
<script>
function code(inputd)
{
var phoneno = /^\d{11}$/;
if(inputd.match(phoneno))
{
return true;
}
else
{
alert("error");
return false;
}
}
</script>
<form>
<input type="text" id='Phone'>
<input type="submit" onclick=return code(document.getElementById("Phone").value);>
</form>
Please try this hope it is helpful.
Use jQuery Keypress event to disallow user to enter any character other than number (0-9).
jQuery(function(){
jQuery("#Phone").keypress(function(){
var value = jQuery(this).val();
value = value.replace(/[^0-9]+/g, '');
jQuery(this).val(value);
});
});
Now, in your validation script, check the length
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
else {
return true;
}
}
Using jquery is very easy. Try with:
<input type='text' id='phoneNum' border=0 value="" />
<input type='submit' id='submitBtn' border=0 value="" />
<script language="JavaScript" type="text/javascript">
$('#submitBtn').click(function(){
var phoneNum = $('#phoneNum').val();
code(phoneNum);
// other code
});
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
</script>
<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.