I am using a online blog form validation which is done in jQuery, The problem I have with this file is when I reuse the input code for a different id, the span alert is not showing up.
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name can't be blank-->
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
$('#contact_nameee').on('input', function() {
var input=$(this);
var is_named=input.val();
if(is_named){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Email must be an email -->
$('#contact_email').on('input', function() {
var input=$(this);
var re = /^[a-zA-Z0-9.!#$%&'*+=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email=re.test(input.val());
if(is_email){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Website must be a website -->
$('#contact_website').on('input', function() {
var input=$(this);
if (input.val().substring(0,4)=='www.'){input.val('http://www.'+input.val().substring(4));}
var re = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
var is_url=re.test(input.val());
if(is_url){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Message can't be blank -->
$('#contact_message').keyup(function(event) {
var input=$(this);
var message=$(this).val();
console.log(message);
if(message){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#contact_submit button").click(function(event){
var form_data=$("#contact").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_"+form_data[input]['name']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{error_element.removeClass("error_show").addClass("error");}
}
if (!error_free){
event.preventDefault();
}
else{
alert('No errors: Form will be submitted');
}
});
});
I have done the jsFiddle .
Please look into it and help me out.
Thank you
The problem is the name of that element, you have added contact_ prefix to the name, remove it and it should be fine
<input type="text" id="contact_nameee" name="nameee"></input>
Demo: Fiddle
Related
I am making an attempt to create my own chatroom using npm, as it stands everything is working smoothly but my main concern is SQL injection or people entering HTML because it will parse anything entered. There is no form being used and the input button, text field and output are all controlled by JavaScript. below is the part of the HTML I am referring to.
<div id="wrapper">
<div class="bubble-container" ></div>
</div>
<div id="sendCtrls">
<input type="text" placeholder="Your message here" id="text">
<button id="myBtn">Send</button>
</div>
This is my .php file which contains all the JavaScript.
<script>
// -------------------------
//var name = prompt('What is your name?');
var name = "<?php echo $_SESSION['username']; ?>";
var bubbles = 1;
var maxBubbles = 60;
var sock = new WebSocket("ws://localhost:5001");
sock.onopen = function() {
var bubble = $("#wrapper");
bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text">\
<p><b>*** Welcome '+name+' to the chat!</b><br>\
These are the rules, please read & follow them.<br>\
1. Be polite in chat.<br>\
2. Keep personal disputes out of chat.<br>\
3. No advertising.<br>\
4. Do not ask to become a Moderator.\
</p></div></div>');
myChat(bubble);
sock.send(JSON.stringify({
type: "name",
data: name
}));
}
// --------------------------
var maxLength = 200; // chars per bubble
sock.onmessage = function(event){
console.log(event);
var json = JSON.parse(event.data);
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p><strong>'+json.name+':</strong> '+json.data+'</p></div></div>');
myChat(bubble);
}
// ---------------------------
document.querySelector('button').onclick = function (){
var text = document.getElementById('text').value;
if(text != "") {
if (text.length < maxLength) {
document.getElementById('text').value='';
sock.send(JSON.stringify({
type: "message",
data: text
}));
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p><strong>'+name+':</strong> '+text+'</p></div></div>');
myChat(bubble);
}else{
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>*** Your message exceeds '+maxLength+' characters!</p></div></div>');
myChat(bubble);
};
}
};
// --------------------------
var input = document.getElementById("text");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
// --------------------------
function myChat(bubble){
$("#msgText").val("");
$(".bubble-container:last").after(bubble);
if (bubbles >= maxBubbles) {
var first = $(".bubble-container:first").remove();
bubbles--;
}
bubbles++;
$('.bubble-container').show(250, function showNext() {
if (!($(this).is(":visible"))) {
bubbles++;
}
$(this).next(".bubble-container").show(250, showNext);
$("#wrapper").scrollTop(9999999);
});
};
</script>
I have not included the server script which is also just JavaScript but can do so if needed. PHP has no interaction with what is being submitted. 2nd question is, will I need to write anything server side to protect against SQL injection or to prevent HTML being entered?
I have this script here that I intend to run:
<script>
$(document).ready(function () {
var sd = $("#StartDate").val();
var ed = $("#EndDate").val();
$("#userReportGenerate").click(function (e) {
e.preventDefault();
console.log(sd);
console.log(ed);
$("<input/>").attr("type", "hidden").attr("id", "uStartDate").attr("name", "StartDate").attr("value", sd).appendTo("userReportForm");
$("<input/>").attr("type", "hidden").attr("id","uEndDate").attr("name", "EndDate").attr("value", ed).appendTo("userReportForm");
console.log($("#uStartDate").val());
return false;
});
});
</script>
However, when I click on the button, I get no value for the uStartDate ID. It just appears as blank on my console.
Is it possible to get the value from this input?
I intend to pass the StartDate and EndDate alongside my form when I submit it.
$(document).ready(function () {
var sd = $("#StartDate").val();
var ed = $("#EndDate").val();
$("#userReportGenerate").click(function (e) {
e.preventDefault();
let uStartDate='<input type="hidden" id="uStartDate" name="StartDate" value="'+sd+'">';
$('#userReportForm').append(uStartDate);
return false;
});
});
I try to learn SAPUI5 with Samples frpm Demo kit Input - Checked. I get an error message: oInput.getBinding is not a function
I have a simple input field xml:
<Label text="Name" required="false" width="60%" visible="true"/>
<Input id="nameInput" type="Text" enabled="true" visible="true" valueHelpOnly="false" required="true" width="60%" valueStateText="Name must not be empty." maxLength="0" value="{previewModel>/name}" change= "onChange"/>
and my controller:
_validateInput: function(oInput) {
var oView = this.getView().byId("nameInput");
oView.setModel(this.getView().getModel("previewModel"));
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var bValidationError = false;
try {
oBinding.getType().validateValue(oInput.getValue());
} catch (oException) {
sValueState = "Error";
bValidationError = true;
}
oInput.setValueState(sValueState);
return bValidationError;
},
/**
* Event handler for the continue button
*/
onContinue : function () {
// collect input controls
var that = this;
var oView = this.getView();
var aInputs =oView.byId("nameInput");
var bValidationError = false;
// check that inputs are not empty
// this does not happen during data binding as this is only triggered by changes
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
// output result
if (!bValidationError) {
MessageToast.show("The input is validated. You could now continue to the next screen");
} else {
MessageBox.alert("A validation error has occured. Complete your input first");
}
},
// onChange update valueState of input
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
Can someone explain to me how I can set the Model?
Your model is fine and correctly binded.
The problem in your code is here, in the onContinue function
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
aInput is not an array, so your code is not iterating on an array element.
To quickly fix this, you can put parentheses around the declaration like this:
var aInputs = [
oView.byId("nameInput")
];
Also, you could remove the first two lines of the _validateInput method since they are useless...
Usually, we set the model once the view is loaded, not when the value is changed. For example, if you would like to set a JSONModel with the name "previewModel", you can do as mentioned below.
Note that onInit is called when the controller is initialized. If you bind the model properly as follows, then the oEvent.getSource().getBinding("value") will return the expected value.
onInit: function(){
var oView = this.getView().byId("nameInput");
oView.setModel(new sap.ui.model.json.JSONModel({
name : "HELLO"
}), "previewModel");
},
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
...
Also, for validating the input text, you can do the following:
_validateInput: function(oInput) {
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var sValueStateText = "";
var bValidationError = false;
if(oBinding.getValue().length === 0){
sValueState = "Error";
sValueStateText = "Custom Error"
}
oInput.setValueState(sValueState);
if(sValueState === "Error"){
oInput.setValueStateText(sValueStateText);
}
return bValidationError;
},
Please note that the code above is not high quality and production ready as it's a quick response to this post :)
I am trying to create an online form using Netsuite.
We have a set for predefined fields like firstname, lastname, etc.
In the same we have a
NLSUBSCRIPTIONS
tag but the field type by default is drop down with multiple select option.
How can I change this drop down to a checkbox?
If you use a custom template you can hide the drop-down and iterate its options to create your own checkboxes.
e.g.
<div class="regFieldWrap">
<span class='cbExpand hideNsLabel'><NLCUSTENTITY_LIST_FIELD></span><input class="otherShadow valid" type="text" name="custentity_list_field_other"><span class="multiProto cbHolder"><input type="radio" name="custentity_list_field"><label class="cbLabel"></label></span>
</div>
and then
<script>
jQuery(function($){
// convert multi select to checkbox
$("span.multiProto").each(function(){
var proto = this;
var selName = $(proto).find("input").attr("name");
var otherCB = null;
$("select[name='"+selName+"']").css({display:'none'}).each(function(){
var sel = $(this);
var isReq = sel.hasClass('inputreq');
if(isReq) sel.removeClass('inputreq');
sel.find("option").each(function(){
if(!this.value) return;
var newby = $(proto.cloneNode(true));
var cb = newby.find("input").val(this.value);
if(isReq) cb.addClass('cb_selectone');
newby.find("label.cbLabel").text(this.text);
$(newby).removeClass('multiProto');
if((/\bother\b/i).test(this.text)){
var otherField = $("input.otherShadow[name='"+ selName+"_other']").each(function(){
var newOther = this.cloneNode(true); // strange but it gets around an IE issue
$(this).remove();
$(newby).find("input").data("conditionalOther", newOther);
newby.get(0).appendChild(newOther);
});
otherCB = newby;
} else proto.parentNode.insertBefore(newby.get(0), proto);
});
sel.get(0).options.length = 0;
});
if(otherCB) proto.parentNode.insertBefore(otherCB.get(0), proto); // make sure this is the end element
});
});
I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});