IsNullOrEmpty attribute - javascript

In HTML exists
required
attribute, which force user to enter some date before submit. But user can type only spaces. Is there attribute which check is typed content is whitespace before postback. In need attibute which works similar to string.IsNullOrWhitespace in c#.

It took me a while to get the Regex right, but the following creates a rule to only select if there's no whitespace:
<input type="text" pattern=".\S*" />
As #Paul S. noted, this isn't checking the first character, so the following will do that:
<input type="text" pattern="^.\S*" />
Also, this does indeed only work in HTML5 browsers, but since the question contained required, I'm assuming there if is some fallback kept in mind.

Using the pattern attribute, you can make it accept only spaces
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" required pattern="\s*"/>
</form>
However, please note that required prevents the submission of empty input (i.e. your "null"), so to permit that remove required so that pattern is doing the requirement checking
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" pattern="\s*"/>
</form>
Lastly, still perform validation on the server as you can never assume a client is a safe source, or conversely, always assume the client is trying to hack you
If you can't assume HTML 5 support, you can shim the behaviour using JavaScript, which would look something like this for required
if(!('required' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i;
for (i = 0; i < inputs.length; ++i)
if (inputs[i].getAttribute('required'))
if (!inputs[i].value)
e.preventDefault(); // + warn?
});
}
and for pattern
if(!('pattern' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i,
re;
for (i = 0; i < inputs.length; ++i)
if (re = inputs[i].getAttribute('pattern')) {
re = new RegExp('^' + re + '$');
if (!re.test(inputs[i].value))
e.preventDefault(); // + warn?
}
});
}
You could also set useCapture to true for the listener to skip ahead in the queue of handlers, letting you prevent the event reaching other handlers in the case of submission prevented

<
<form onsubmit="alert('Submitted.');return false;"> <input type="text" required="" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" value="" name="dates_pattern2" id="dates_pattern2" list="dates_pattern2_datalist" placeholder="Try it out." autocomplete="off"> <input type="submit" value="»"> <datalist id="dates_pattern2_datalist"> </datalist> </form>

Related

Selecting all textbox at once with javascript

In my work we have to fill a lot of textboxes to do some validations. After all, we need to erase all - one by one - to restart the process.
Has some way to erase all textbox content with javascript (the only one method we can use now)? A for loop maybe?
You should put all the input fields in a form and then reset the form by the .reset() method.
document.getElementById("reset").onclick= ()=>{
document.getElementById("form").reset()
}
<form id="form">
<input/>
<input/>
</form>
<button id="reset">Reset</button>
See an example on W3Schools or the docs on MDN
If you want to restore the fields to their initial value, reset the form as suggested by #dota2pro's answer.
OTOH, if you want to clear the elements regardless of their initial value, you can query the elements using a type (aka "tag") CSS selector via Document​.query​SelectorAll()
and iterate through the elements as below:
function go() {
let inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
}
<input type="text" value="a"><br>
<input type="text" value="b"><br>
<input type="text" value="c"><br>
<br>
<button onclick="go()">click to clear</button>
Note that:
document.querySelectorAll('input') fetches all <input>s regardless of their type attribute.
document.querySelectorAll('input[type="text"]') fetches all <input type="text">.
document.querySelectorAll('textarea') fetches all <textarea>.
If you want to combine, you can use the comma combinator:
document.querySelectorAll('input[type="text"],textarea')
You can get in different ways in javascript:
By ID : document.getElementById("id")
By class: document.getElementsByClassName("class")
By tag:
document.querySelectorAll("input")
or Jquery
By ID : $("#id")
By class: $(".class")
By tag: $("input")
Read documentation about that here
tru
[...document.querySelectorAll('input')].map(x=>x.value='')
var clean = () => [...document.querySelectorAll('input')].map(x=>x.value='');
<button onclick="clean()">Clear</button><br>
<input type="text" value="some"><br>
<input type="text" value="short"><br>
<input type="text" value="text"><br>
Bellow code will select all editable text-boxes
document.querySelectorAll('input[type="text"]:not(:disabled):not([readonly]))')
If you have JQuery available, you can do:
$('input[type="text"]').val('');
Or, if you prefer native:
for(var i = 0; i < document.getElementsByTagName('input').length; i++){
document.getElementsByTagName('input')[i].value = '';
}

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Check if html form values are empty using Javascript

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.

getElementById is returning null

I'm attempting to read in a file using this form in my :
<form name="UploadForm" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a CSV file to upload: <input name="upload_file" type="file" /><br />
<input type="submit" value="Upload" onClick="uploadFile()" />
</form>
But when I go to read the value in this function within I receive a "cannon find "elements" of null error:
function uploadFile() {
var file = document.getElementById('UploadForm').elements['upload_file'].value;
var allTextLines = file.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
alert(lines);
};
Does anybody have any ideas as to what I'm doing wrong?
getElementById returns the element with the specified id, but the form doesn't have an id at all. You are using the obsolete name attribute (which was superseded by id when HTML 4 was released in 1998).
Change it to:
<form id="UploadForm" method="post">
(N.B. name is not obsolete on form controls, such as input and select)
Note that your event handler isn't cancelling the default behaviour of the submit button. So as well as running the JS, you will immediately submit the form, leave the page, and cancel the JS (if it does anything asynchronous, which the name suggests it will be).
If you are going to use intrinsic event attributes, then you need to return false if the JavaScript succeeds.
I recommend giving them up in favour of addEventListener though.
Change your input tag to be like this:
<input name="upload_file" id="upload_file" type="file" />
Also change this line from:
document.getElementById('UploadForm').elements['upload_file'].value
to
document.getElementById('upload_file').value

Javascript form validation only works in firefox

I am relatively new to Javascript so I'm hoping this is a simple mistake. I building a generic form validation function that is called on the form's onSubmit. The function loops through all the form's child elements, looks for certain classes, and analyzes the contents of the appropriate fields. If it finds something missing or erroneous, it displays the appropriate error message div and returns false, thus preventing the form from being submitted to the php page.
It works well in firefox 3.6.3, but in every other browser I've tested (Safari 4.0.4, Chrome 4.1, IE8) it seems to ignore the onSubmit and jump straight to the php processing page.
HTML CODE:
<form name='myForm' id='myForm' action='process_form.php' method='post' onSubmit="return validateRequired('myForm')">
<fieldset class="required radioset">
<label for='selection1'>
<input type='radio' name='selection' id='selection1' value='1'/>
Option 1
</label>
<label for='selection2'>
<input type='radio' name='selection' id='selection2' value='2'/>
Option 2
</label>
<label for='selection3'>
<input type='radio' name='selection' id='selection3' value='3'/>
Option 3
</label>
<label for='selection4'>
<input type='radio' name='selection' id='selection4' value='4'/>
Option 4
</label>
<div class='errorBox' style='visibility:hidden'>
Please make a selection
</div>
</fieldset>
<fieldset class="required checkset">
<label>
Choice 1
<input type='checkbox' name='choices' id='choice1' value='1'/>
</label>
<label>
Choice 2
<input type='checkbox' name='choices' id='choice2' value='2'/>
</label>
<label>
Choice 3
<input type='checkbox' name='choices' id='choice3' value='3'/>
</label>
<label>
Choice 4
<input type='checkbox' name='choices' id='choice4' value='4'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please choose at least one
</div>
</fieldset>
<fieldset class="required textfield" >
<label for='textinput1'>
Required Text:
<input type='text' name='textinput1' id='textinput1' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please enter some text
</div>
</fieldset>
<fieldset class="required email textfield">
<label for='email'>
Required Email:
<input type='text' name='email' id='email' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
The email address you have entered is invalid
</div>
</fieldset>
<div>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
</div>
</form>
JAVASCRIPT CODE:
function validateRequired(id){
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
/*RADIO BUTTON or CHECK BOX SET*/
if(hasClass(elem,"radioset") || hasClass(elem,"checkset")){
var inputs = elem.getElementsByTagName("input");
var check = false;
for(j = 0; j < inputs.length; j++){
if(inputs[j].checked){
check = true;
}
}
if(check == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
/*TEXT FIELD*/
else if(hasClass(elem,"textfield")){
var input = elem.getElementsByTagName("input");
if(input[0].value == ""){
errors += 1;
showError(elem);
} else {
hideError(elem);
/*EMAIL ADDRESS*/
if(hasClass(elem,"email")){
if(isValidEmail(input[0].value) == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
}
}
}
}
if(errors > 0){
returnVal = false;
} else {
returnVal = true;
}
return returnVal;}
I know this is a lot of code to look at, but any help would be appreciated. Since it works fine in one browser, Im not sure how to start debugging.
Thanks
Andrew
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
The problem is that your required and other classes are put on the <fieldset> element.
Fieldset elements are included in the form.elements collection on IE, Firefox and Opera, but not WebKit browsers (Chrome, Safari). It is these browsers where your form fails for me.
It has always been a weird quirk that <fieldset> was included in the elements collection. The DOM Level 2 HTML spec states that only ‘form control elements’ should be present in the collection, and by HTML4's definition that would seem not to include fieldsets, which have no control name or value.
You could perhaps change your code to use getElementsByTagName to pick up the fieldsets instead:
var fieldsets= form.getElementsByTagName('fieldset');
for (var i= 0; i<fieldsets.length; i++) {
var elem= fieldsets[i];
I would not use hasClass. Here's another way to try that might work better for you:
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
// do something here with a <input type="text" .../>
alert(node.value);
}
}
I know that IE has problems getting the classes from some elements which have multiple classes associated with them. Regardless, this is a handy function.
If you have any kind of JavaScript error, the function will not return false, and therefore the default behavior of submitting the data will be triggered.
Try running your code through [http://www.javascriptlint.com/online_lint.php][1] first, then a debugger.
try not to use if(errors > 0)...just in every condition (for wrong input) put return false;
and at the end before the last bracket put return true;
and better use:
onSubmit="return validateRequired(this)"
and there is no need in this lines (in case you remove the errors var)
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
Not the cause of your problem, I'm sure, but it's best not to serve a set of radio buttons without one of them selected.
In your particular case, if you know that you set one when you serve the page, you don't need a "required" check; there's no way the user can get the radio buttons into a state where none are selected. Pick a sensible default, make it the first option, and make it selected. Simplify your life :)
From the W3C:
http://www.w3.org/TR/html401/interact/forms.html#radio
If no radio button in a set sharing
the same control name is initially
"on", user agent behavior for choosing
which control is initially "on" is
undefined. Note. Since existing
implementations handle this case
differently, the current specification
differs from RFC 1866 ([RFC1866]
section 8.1.2.4), which states:
At all times, exactly one of the radio
buttons in a set is checked. If
none of the <INPUT> elements of a set
of radio buttons specifies `CHECKED',
then the user agent must check the
first radio button of the set
initially.
Since user agent behavior differs,
authors should ensure that in each set
of radio buttons that one is initially
"on".
Back to basics for a second: You say it "seems to ignore the onsubmit". That leaves three possibilities that I can think of:
Your function is never called
It's called, and is bombing out part-way through due to an error
It's called, and isn't doing what you think it is, always returning true
It's not clear from your question which it is, so if I were you I'd start debugging this by putting an alert at the beginning of the function to see whether IE's calling it at all - then move that alert down and run the validation again, and see where it stops appearing (any error must be above that point).
I'd also want to alert the return value from the place it was called, to see what was coming back. If it's always true, then your code is working but not doing what you think it does.
From there, you at least have a clearer grasp of what's going on, if not an exact block of code to be scrutinising.

Categories