set focus to textbox form element following Validation - javascript

I have a number of fields on a form that I perform Validation on, which I then want to Focus on if the validation fails. The Validation works fine, i.e. rtnStr, but the focus() just won't land on any of the textbox fields, i.e. vCtrl. It remains on the Submit button.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = "txtforename";
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = "txtSurname";
}
}
if (rtnStr != "") {
alert(rtnStr)
window.setTimeout(function () {
document.getElementById(vCtrl).focus();
}, 0);
return false;
}
else {
return true;
}
}
</script>

The problem is that vCtrl is a string which is the name of a form and not the id which document.getElementById(vCtrl).focus() is looking for. The way to fix this is to make vCtrl store the DOM element instead of a text string.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtforename;
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtSurname;
}
}
if (rtnStr != "") {
alert(rtnStr)
vCtrl.focus();
return false;
}
else {
return true;
}
}
</script>
jsfiddle

Related

jQuery validate textbox 1 if there is same multiple value inside textbox 2

I have 2 textbox.
<input type="text" id="pcbaSerialNo"/>
and
<input type="text" id="pcbaSerialNoMask"/>
and the js
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
The js function will run on enter key in textbox.
When scan on textbox #pcbaSerialNo, it will send the value to #pcbaSerialNoMask. (Example more than 1 value will be: test1, test2)
Now I need to validate #pcbaSerialNo to detect if there is same value.
My question, how to validate that textbox to prevent same value(duplicate)?
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>
Just add below line before checking for existing value. You have to convert the string value to array while using inArray function.
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>

Check if input fields are filled out in a form

I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});

Javascript validation is not working in aspx page for allvalidate()

Here is my code:
<script type="text/javascript">
function Allvalidate() {
var ValidationSummary = "";
ValidationSummary += NameValidation;
ValidationSummary += EmailValidation;
ValidationSummary += MobilenumValidation;
if (ValidationSummary != "") {
alert("ValidationSummary");
return false;
}
else {
alert("Information Submitted Successfuly");
return true;
}
}
function NameValidation() {
var userid;
var controlid = document.getElementById("<%=Textusername.ClientID%>");
userid = controlid.value;
var val = /^[a-zA-Z]+$/;
if (userid == "") {
alert ("Enter your name" + "\n");
}
if (val.test(userid))
{
return "";
}
else{
alert("Name accepts only spaces and character" + "\n");
}
}
function EmailValidation() {
var userid;
var controlid = document.getElementById("<%=Textemail.ClientID%>");
userid = controlid;
var val = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (userid == "") {
alert("Enter your name" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("Email should be like this example xyz#abc.com");
}
}
function MobilenumValidation()
{
var userid;
var controlid = document.getElementById("<%=Textmobilenum.ClientID%>");
userid = controlid;
var val = /^[\d\.\-]+$/;
if (userid == "") {
alert("Enter your Mobile Number" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("PhoneNumber should be only in digits ");
}
}
</script>
aspx:
<asp:Button ID="btnsub" runat="server" Text="Submit"
OnClick="btnsub_Click" OnClientClick="javascript:Allvalidate()" />
The above code is not working, if i enter invalid mobile number,name and email it will accepted.
May i know, what is my mistake?
Thanks,

Regex not firing on user form

My Regex for email does not seem to be working, it does not fire,
the validation on the form passes even if the user only inputs a single .
here is my code:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
$.each(a, function (index, value) {
if (sMsg == "") {
if ($("#" + value).val().trim() == "") {
var sText = $('td:first', $($("#" + value)).parents('tr')).text();
sMsg = "Please enter a " + sText;
$("#" + value).focus();
}
}
});
if (sMsg == "") {
if ($("#txtPhone").val().trim() == "" && $("#txtMobile").val().trim() == "") {
sMsg = "Please enter a phone or mobile number";
$("#txtPhone").focus();
}
}
if (sMsg == "") {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!regex.test($("#txtEmail").val())) {
sMsg = "Please enter a valid email address";
}
}
break;
i have now resolved this, turns out there was a primary validation on the email field to check whether it contains a value, i simply removed this and it worked
amended this line:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
to
var a = ["txtTitle", "txtSurname","txtPostCode"];

Radio button validation through JavaScript

I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}

Categories