JQ and Js how to Validate content null (Spacebar) - javascript

My JS Here:
$('input[type=submit]').click(function () {
var val = $('#message_content').sceditor('instance').val();
if( val == "" || !val ) {
alert('Content Cannot Null');
return false;
}
return true;
});
I have one question:
How to validate? If all content is " "(Spacebar) or "   "(full code Spacebar)...Judgment the content is null?

$('input[type=submit]').click(function () {
var val = $.trim($('#message_content').sceditor('instance').val());
if(!val) {
alert('Content Cannot Null');
return false;
}
return true;
});
You can try this.

Trim the whitespace from the input and then check it against ""

Related

onsubmit verify that all functions return true

i have about 6 form inputs that i have javascript running validation on, how would i go about verifying that all functions return as true? here are two samples of my javascript functions
$(document).ready(function() {
//First Name Input Field
$( "#first_name" ).focusout(function() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("First Name* is required so my response won't go to spam");
return false;
} else {
var re = /^[A-Za-z-]+$/;
if(re.test(document.getElementById("first_name").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("First Name* not a valid name");
return false;
}
}
});
//Last Name Input Field
$( "#last_name" ).focusout(function() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("Last Name* is required so my response won't go to spam");
return false;
} else {
var re = /^[A-Za-z-]+$/;
if(re.test(document.getElementById("last_name").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Last Name* not a valid name");
return false;
}
}
});
});
Add default variables and set as true.
And when error occurred overwrite the value as false.
Idea is that:
$(document).ready(function() {
var firstnameStatus = true;
var lastnameStatus = true;
if(firstname have error){
// your code
var firstnameStatus = false;
}
if(lastname have error){
// your code
var lastnameStatus = false;
}
if( firstnameStatus == true && lastnameStatus == true){
alert('all fields true');
}
});

Validate input value before it is shown to user

I have an html <input> and some pattern (e.g. -?\d*\.?\d* float-signed value).
I should prevent typing the not matched value.
I did it in next way
jQuery.fn.numeric = function (pattern)
{
var jqElement = $(this), prevValue;
jqElement.keydown(function()
{
prevValue = jqElement.val();
})
jqElement.keyup(function(e)
{
if (!pattern.test(jqElement.val()))
{
jqElement.val(prevValue);
e.preventDefault();
}
prevValue = ""
})
};
JSFiddle DEMO
But in this case, value is shown to user and then corrected to right value.
Is it way to vaidate value before it is shown to user?
I can use pattern attribute from html5
$("#validateMe").on('keydown', function() {
var charBeingTyped = String.fromCharCode(e.charCode || e.which); // get character being typed
var cursorPosition = $(this)[0].selectionStart; // get cursor position
// insert char being typed in our copy of the value of the input at the position of the cursor.
var inValue = $(this).value().substring(0, cursorPosition) + charBeingTyped + $(this).value().substring(cursorPosition, $(this).value().length);
if(inValue.match(/-?\d*\.?\d*/)) return true;
else return false;
});
How about this POJS, I'm using a cross-browser addEvent function instead of jquery and not using any regexs, but I believe it achieves what you are looking for. Pressing + or - changes the sign of the value.
HTML
<input id="test" type="text" />
Javascript
/*jslint maxerr: 50, indent: 4, browser: true */
(function () {
"use strict";
function addEvent(elem, event, fn) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(null, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return ret;
}
function attachHandler() {
window.event.target = window.event.srcElement;
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return ret;
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
function verify(e) {
var target = e.target, // shouldn't be needed: || e.srcElement;
value = target.value,
char = String.fromCharCode(e.keyCode || e.charCode);
if (value.charAt(0) === "-") {
if (char === "+") {
e.target.value = value.slice(1);
}
} else if (char === "-") {
e.target.value = char + value;
return false;
}
value += char;
return parseFloat(value) === +value;
}
addEvent("test", "keypress", verify);
}());
On jsfiddle
I think I used the correct values keyCode || charCode
but you may want to search and check. A summary of the correct ones are available here
You could use this code to find out what character is pressed. Validate that character and, if it validates, append it to the input field.
Try this code:
jQuery.fn.numeric = function (pattern)
{
$(this).keypress(function(e)
{
var sChar = String.fromCharCode(!e.charCode ? e.which : event.charCode);
e.preventDefault();
var sPrev = $(this).val();
if(!pattern.test(sChar)){
return false;
} else {
sPrev = sPrev + sChar;
}
$(this).val(sPrev);
});
};
$("#validateId").numeric(/^-?\d*\.?\d*$/);
jsfiddle.net/aBNtH/
UPDATE:
My example validates each charachter while typing. If you prefer to check the entire value of the input field instead, I would suggest to validate the value on an other Event, like Input blur().

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

SlickGrid- Need of insensitive case filter

Is there's a way to change the filter from sensitive case to insensitive?
Thank you.
Here’s the relevant section of a working example using the DataView filter. Notice the searchString variable is converted to lowercase when the value is first defined and then it's compared to lowercase strings within the myFilter function.
function myFilter(item, args) {
if (args.searchString != "" && item["FirstName"].toLowerCase().indexOf(args.searchString) == -1 && item["LastName"].toLowerCase().indexOf(args.searchString) == -1) {
return false;
}
return true;
}
....
$("#txtSearch").keyup(function (e) {
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value.toLowerCase();
updateFilter();
});
function updateFilter() {
dataView.setFilterArgs({
searchString: searchString
});
dataView.refresh();
}
// initialize the model after all the events have been hooked up
dataView.beginUpdate();
dataView.setItems(data);
dataView.setFilterArgs({
searchString: searchString
});
dataView.setFilter(myFilter);
dataView.endUpdate();
Guessing you are talking about the DataView filter, the implementation of the filter functionality is totally up to you. Note the filter function used in the SlickGrid examples - that function is set as the filter using dataView.setFilter(your_function_here). So implement the filter function as you want and set it to the dataView
function filter(item) {
// String Should Match Each Other
/* for (var columnId in columnFilters) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var c = grid.getColumns()[grid.getColumnIndex(columnId)];
if (item[c.field] != columnFilters[columnId]) {
return false;
}
}
} */
for (var columnId in columnFilters) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var c = grid.getColumns()[grid.getColumnIndex(columnId)];
// This Case Sensitive
//if (!(item[c.field] && (""+item[c.field]).indexOf(columnFilters[columnId]) !== -1)) {
if (!(item[c.field] && (""+item[c.field].toLowerCase()).indexOf(columnFilters[columnId].toLowerCase()) !== -1)) {
// Case in-Sensitive
return false;
}
}
}
return true;
}

Problem in make a date input mask

How do I make a date input masked (hidden) without using a plugin, as followed:
Formating: YYYY/MM/DD = showing in the input as => ____/__/__
This is my code that doesn't work:
$('.date_input').delegate("input.date:text", 'keyup', function () {
//var dateMMDDYYYRegex = '^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$';
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{3,3}/g).join("/").match(/./g).reverse().join("");
$(this).val($val)
});
Example of the code
$('.date_input').delegate("input.date:text", 'keypress', function (e) {
var char = getChar(e || window.event);
if (char != "/")
{
this.value += "_";
return false;
}
});
function getChar(event) {
if (event.which == null) {
return String.fromCharCode(event.keyCode) // IE
} else if (event.which!=0 && event.charCode!=0) {
return String.fromCharCode(event.which) // the rest
} else {
return null // special key
}
}
//You can replace getChar with the jQuery equivalent.

Categories

Resources