I have jQuery validation for my input fields. But seems like not working :(
$('form')
.submit(function() {
var name = $.trim($('#TxtName').val());
var dob = $.trim($('#TxtDesig').val());
var salary = $.trim($('#TxtSalary').val());
if (name === "" || dob === "" || salary ==="") {
alert("All fields are mandatory");
}
return false;
});
Here is my html form:
<form class="form-group" method="post">
<label class="control-label">Employee Name:</label>
<input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" /><br />
<label class="control-label">Designation:</label>
<input class="form-control" type="text" id="TxtDesig" name="Designation" value="" /><br />
<label class="control-label">Salary:</label>
<input class="form-control" type="date" id="TxtSalary" name="Salary" value=""/><br/>
Here is how to code your jQuery validation.
I need to show it in a fiddle since the stacksnippet does not allow form submit
https://jsfiddle.net/mplungjan/n6mcyf6x/
$(function() {
$('form').on("submit", function(e) {
var name = $.trim($('#TxtName').val());
var dob = $.trim($('#TxtDesig').val());
var salary = $.trim($('#TxtSalary').val());
if (name === "" || dob === "" || salary === "") {
alert("All fields are mandatory");
e.preventDefault();
}
});
});
As mentioned by Rhys Bradbury an alternative is to add "required" to each field .
It may however not be supported by older browsers (like IE<10) for example)
http://caniuse.com/#feat=form-validation
Why do this in jQuery? Why not use HTML required attribute on form inputs?
ref:
http://www.w3schools.com/jsref/prop_text_required.asp
example:
<input placeholder="required a value here please" required/>
FYI this is HTML5
You can validate by two process.
process 1: Add following attribute into validated controls as one I edited from your source. Easiest way rest will be responsible of jQuery validation engine.
<input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" required='' data-msg-required='Please provide name.'/>
Process 2: If you want your controlled validation then you need write piece of code as follows.
$("#form").validate({
rules:{ //Validation rules work on name attribute
EmployeeName:{ //Condition Area
required:true
}
},
messages:{ //user information area
EmployeeName:
{
required:"Please provide Employee Name" /// Message to user for required fields
}
}
});
You get more information from jQuery Website
Related
This question already has answers here:
JavaScript validation for empty input field
(15 answers)
Closed 3 years ago.
I have a big form with lot of fields and most of them are required fields. so i wanted to show pop-up alert message saying please fill required field.
<input name="fname" id="fname" type="text" class="form-control" required>
also i m showing usual message below that particular field,
i need something like on submit click
If (some fields required field error got triggered )
{
show alert pop-up message ;
}
I am new to this thing so..
function checkEmpty()
{
var fname = document.getElementById('fname').value;
if(!fname)
{
alert('Field is empty')
}
}
<form onsubmit='checkEmpty'>
<!--Form contents-->
</form>
Validation with javscript can easily be bypassed since it happens in the client side.
Try this
<form onsubmit="myFunction()">
<input name="fname" id="fname" type="text" class="form-control" required>
<form>
Use the following Function to check fields
function myFunction() {
var fname=document.getElementById('fname').value;
if(!fname)
{
alert("please fill required field");
}
}
You can check multiple fields in if conditions by putting || Sign. eg you have 2 filed fname and lname. You can check by if(!fname || !name)
You need to show overall alert as well as individual error message below each required field.
To do so using jQuery,
<form>
<input name="fname" id="fname" type="text" class="form-control validateclass" required>
<span class="spnError"></span>
<input name="lname" id="lname" type="text" class="form-control validateclass" required>
<span class="spnError"></span>
<input id="btnClick" type="button" value="Submit Form"/>
</form>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function()
{
$(".validateclass").each(function() {
var fieldValue =$(this).val();
if(fieldValue == null || fieldValue == "")
{
$(this).next().css( "color", "red" ).text("Field is required");
}
else
{
$(this).next().text("");
}
});
});
});
</script>
So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.
I want to validate my fields using AngularJS's own form validation. However, I only want to check some of the fields when other fields have data. E.g.
<form novalidate name="myForm" ng-submit="submitThisForm()">
<h1>Shipping address</h1>
<!-- These are the inputs -->
<input name="sAddress1" type="text" ng-model="sAddress1" required>
<input name="sAddress2" type="text" ng-model="sAddress2" required>
<input name="sAddress3" type="text" ng-model="sAddress3">
<!-- These are the errors -->
<div class="error" ng-show='(myForm.sAddress1.$invalid) && myForm.submitted'>Required</div>
<div class="error" ng-show='(myForm.sAddress2.$invalid) && myForm.submitted'>Required</div>
<h1>Billing address (if different)</h1>
<!-- These are the inputs -->
<input name="bAddress1" type="text" ng-model="bAddress1" required>
<input name="bAddress2" type="text" ng-model="bAddress2" required>
<input name="bAddress3" type="text" ng-model="bAddress3">
<!-- These are the errors -->
<div class="error" ng-show='(myForm.bAddress1.$invalid) && myForm.submitted'>Required</div>
<div class="error" ng-show='(myForm.address2.$invalid) && myForm.submitted'>Required</div>
</form>
Basically, the Billing address is optional, but once any part of it is filled in, bAdress1 and bAddress2 become Required. How do I achieve this?
(The variable myForm.submitted is set to false on page load, and then set to true when the form is submitted, so it only shows once validation has taken place.) I prefer vanilla JS answers, but I am using jQuery for this project, so that is also okay.
EDIT: Here's the answer with a pretty, formatted layout:
In the HTML file:
<input name="bAddress1" type="text" ng-model="bAddress1" ng-required="doWeNeedThis()"/>
<input name="bAddress2" type="text" ng-model="bAddress2" ng-required="doWeNeedThis()"/>
<input name="bAddress3" type="text" ng-model="bAddress3"/>
In the JS file:
$scope.doWeNeedThis = function() {
if((document.getElementsByName("bAddress1")[0].value != "")
|| (document.getElementsByName("bAddress2")[0].value != "")
|| (document.getElementsByName("bAddress3")[0].value != "")) {
return true;
} else {
return false;
}
};
Many thanks to Davin for the quick (and complete) answer.
ng-required will allow you to run an expression to determine whether the field is required or not.
<input name="bAddress1" type="text" ng-model="bAddress1" ng-required="doWeNeedThis()">
ng-required is documented with form.
So, in your example, you could implement doWeNeedThis() function in your controller and check the values of your model to determine if the input should be required or not.
Otherwise, in simple cases, you can just write the expression directly into the ng-required expression:
<input name="bAddress1" type="text" ng-model="bAddress1" ng-required="bAddress1 || bAddress2">
Have a basic registration form, trying to validate it.
I am using form serializeArray() method and loop trough the form and find if the values are null.
HTML CODE
<form name="reg" id="regform">
<fieldset>
<label for="firstname">First Name</label>
<input type="text" name="firstname" value="First Name"/>
</fieldset>
<fieldset>
<label for="lastname">Last name</label>
<input type="text" name="lastname" value="Last Name"/>
</fieldset>
<fieldset>
<label for="date">Age</label>
<input type="text" name="age"/>
</fieldset>
</form>
JQUERY Code
var formElements = $("#regform").serializeArray();
$(formElements).each(function(x)
{
if(formElements[x]["value"] == "")
{
$("[name='" + formElements[x]['name'] +"']").addClass('error');
}
});
From the above code i am able to add the class ".error" when the value is null.
Now i want the code to check the text fields values are not the default values like in my case the default values are "First Name" "Last Name"..
So i want to check even for the default values and add error class to respective element and even focus back the cursor on the first null value text field
Thanks in advance
I highly suggest using http://docs.jquery.com/Plugins/Validation. You can test for various things, such as blank values, and even extend it to detect default values.
For example:
$.validator.addMethod("name", function(value) {
return value != "First Name";
}, 'Please enter your first name.');
Alternatively you can just test against a default value with jQuery's data() function:
Working Demo: http://jsfiddle.net/WpQ2n/2/
var input = $(".name"),
defaultval = input.data("default", input.val());
// Can't submit forms in jsfid, so i just used a click event.
// Change to .submit()
$("input[type='submit']").on("click",function(e){
if(input.val()== input.data("default")){
input.addClass("error");
}
else{
// Yay it validated...
input.removeClass("error");
}
e.preventDefault();
});
im trying to validate a form before its submitted to the database but something seems to be conflicting with it and its just sending anyway without any values
heres my form:
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<span style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px;">Ally McCoist will be sacked on</span>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/submit-button-small.png" name="submit" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres my validate javascript:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(e){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
i also have this javascript on the page fore my jquery UI datepicker which i think might be causing the problem
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
fingers crossed one of you can see something that might fix this problem
It is possible that the form was filled out by a person with JavaScript disabled or that a person or machine simply invoked an HTTP POST, with whatever values they saw fit. For this reason, it is necessary to perform validation on the server-side (i.e. in send.php), not just on the client-side (in the JavaScript file). JavaScript validation is really just a UI optimization that allows a user to be immediately told that something is wrong without requiring a round-trip communication to the server. From a user-interface perspective, JavaScript validation is important, but from a security perspective it is useless.