Textarea maxlength validering

mobx-form-validation-kit

2019.11.05 10:06 russ_dragon mobx-form-validation-kit

Hi.
Today I want to talk about a new package for asynchronous validations in projects that are based on React, Mobx and written in Typescript. Modern Frontend development involves a large amount of logic when filling out pages with documents, questionnaires and documents for a loan, payment orders, registration pages on the site. The main logical burden falls on validation checks. Angular developers thought over this point and offer developers to use the built-in FormControl mechanism for these purposes, which, although it has a number of drawbacks, is still better than the complete absence of such a solution on React. The situation is complicated by the fact that the current trend of React development involves the use of mobx to organize business logic. Faced with these problems, we solved all of them by writing a package: @mobx-form-validation-kit

Pluses of the package

Installation

npm install @quantumart/mobx-form-validation-kit 

FormControl

@ quantumart/mobx-form-validation-kit allows creating a layer between the source data and the display form. Which, in turn, allows validating them and, if necessary, changing the data before incorporating to the original object. The @ quantumart / mobx-form-validation-kit library contains three main classes (validation components) for managing the form:
Name Description
FormGroup allows combining validation components together. The class is typed and allows remaking the interface with the list of fields as a generic parameter. "Any" is specified by default, it is highly recommended not to use it without typing, despite there is a possibility.
FormControl is used to validate a specific field, the most commonly used class. The class is typed, and it takes the type of variable, which it should store, as a generic parameter. "String" is specified by default, because the default is string-type, as the most common option for forms.
FormArray allows creating and managing an array of variational components.
In addition, there are basic abstract classes
Name Description
AbstractControl is a base class for all listed validation classes, it is not typed.
FormAbstractControl is a base class for FormGroup and FormArray, it is not typed.
FormAbstractGroup is a non-typed base class for FormControl, contains a link to the html element that is being rendered.
The best practice for creating a validating form would be the following idea. An object of the single FormGroup type is created for the form and the fields are listed therein
this.form = new FormGroup({ name: new FormControl( this.userInfo.name, [], v => (this.userInfo.name = v) ), surname: new FormControl( this.userInfo.surname, [], v => (this.userInfo.surname = v) ) // … }); 
FormGroup supports nesting, i.e.
this.form = new FormGroup({ name: new FormControl( this.userInfo.name, [], v => (this.userInfo.name = v) ), surname: new FormControl( this.userInfo.surname, [], v => (this.userInfo.surname = v) ) passport: new FormGroup({ number: new FormControl( this.userInfo.passport.number, [], v => (this.userInfo.passport.number = v) ), // … }) // … }); 
FormArray may be added, to which in turn the FormControl type and/or the entire FormGroup may be transferred, creating objects of any complexity and structure.
  • FormArray>
  • FormArray>
FormControl itself takes the following set of parameters into the constructor
Name Description
value is an initial typed value or its getter function. In the case of using the observed values ​​inside the getter function, a subscription is being performed to change them; at the end of use, it is required to call formControl.dispose() to unsubscribe.
validators is a set of validators.
callbackValidValue is a callback function, to which the last valid value is transferred. It is called every time a value in FormControl changes and this value passes the described validations.
activate is a function, which enables/disables validations by condition (always enabled by default). For example, the validity of the end date of a service does not need to be controlled if "Unlimited" box is not checked. As a result, by simply entering a function here that checks the state of the observable field responsible for the "Unlimited" checkbox, it is possible to automatically disable all validations associated with the field for checking the date, instead of specifying this logic in each of the date field validations.
additionalData is a block with additional information, it allows supplementing additional information to a specific FormControl and use it later, for example, for visualization. This is convenient if there are builders for FormControl, in which it is required to hardcode certain information, rather than transferring this information through a complex data bundle to the controls for visualization. Although I cannot give an exact and undeniable application scenario, it is better to have such a possibility than to suffer without it.
There is one restriction, which is present in FormControl from Angular as well; there is no need to reuse objects on different forms. That is, it is possible to create a FormGroup builder and to create own object on each page. But using one object per bunch of pages is the bad practice. Moreover, FormControl is initialized with a single value, and if this value is changed, the new one will not get into FormControl. This is done on purpose, because, as the practice has shown, for some reason, everyone first tries to edit the source object bypassing validations, instead of the value in FormControl. Just assign a new value to the value field of FormControl to modify the source object. FormGroup takes the following set of parameters into the constructor:
Name Description
controls is an object inherited from AbstractControls. Actually, just create an interface inherited from AbstractControls, in which you list fields of the FormGroup, FormControl,
validators is a set of validators for group values. For example, it is possible to create FormGroup containing two values, the minimum and maximum date, for the period selection control. It is in these validators that the function/functions of validation the date range will be required to transfer. For example, that the start date does not exceed the end date
activate is a function, which enables/disables validations by condition (always enabled by default). It should be understood that enabling the validation function to a group disables the validation at the level of the entire group. For example, we have a drop-down box for an identity document. It is possible to create several FormGroup with a various set of fields for documents: passport, driver’s license, seafarer's ID, etc. In this function, the drop-down box values should be validated, and if the selected value does not correspond to this group, all validation checks are disabled. To be more precise, the group will be considered valid, regardless of the values there​​in.
Let's talk about the FormControl fields which are present both in FormGroup and in FormArray.
Name Description
ControlTypes is a type of control (Control, Group, Array)
processing means in the process of analysis. Because asynchronous validations are supported, for example, those that require a server request. The current state of the validation may be found in this field.
Moreover, FormGroup andFormArray support the wait method, which allows waiting for the validation to complete. For example, when you click on the "send data" button, the following structure should be specified.
await this.form.wait(); if (this.form.invalid) { … 
Name Description
disabled , an error checking is disabled (control is always valid)
active , an error checking is enabled. Depends on the result of the activation function. This value is very convenient to use to hide a group of fields on the form and not write additional and duplicate functions of business logic.
invalid for FormControl means that the field contains validation errors. For FormGroup andFormArray, this means either the very group control contains errors, or one of the nested fields (at any of the nesting levels) contains validation errors. THat is, to check the validity of the entire form, it is enough to perform a single check of "invalid" or "valid" of the upper FormGroup.
valid for FormControl means that the field does not contain validation errors. For FormGroup and FormArray, this means either the very group control does not contain errors, or none of the nested fields (at any of the nesting levels) contains validation errors.
pristine the value in the field did not change after initialization with the default value.
dirty the value in the field changed after initialization with the default value.
untouched for FormControl means that the field (for example, "input") was not in focus. For FormGroup and FormArray, this means that none of the nested FormControls was in focus. The "false" value in this field means that the focus was not only set to, but also removed from the field.
touched for FormControl means that the field (for example, "input") was in focus. For FormGroup andFormArray, this means that one of the nested FormControls was in focus. The "true" value in this field means that the focus was not only set to, but also removed from the field.
focused for FormControl means that the field (for example, "input") is now in focus. For FormGroup andFormArray, this means that one of the nested FormControls is now in focus.
errors the field contains validation errors. Unlike the fields listed, this array contains exactly the errors of either FormControl, or FormGroup, or FormArray, i.e., errors of this control, but not of all nested ones. Affects the "valid/invalid" field
warnings the field contains "Warning" messages. Unlike the fields listed, this array contains exactly the errors of either FormControl, or FormGroup, or FormArray, i.e., messages of this control, but not all the embedded ones. Does not affect the "valid/invalid" field
informationMessages the field contains informational messages. Unlike the fields listed, this array contains exactly the errors of either FormControl, or FormGroup, or FormArray, i.e., messages of this control, but not all the embedded ones. Does not affect the "valid/invalid" field
successes the field contains additional validity messages. Unlike the fields listed, this array contains exactly the errors of either FormControl, or FormGroup, or FormArray, i.e., messages of this control, but not all the embedded ones. Does not affect the "valid/invalid" field
maxEventLevel() the maximum level of validation messages that are currently in the field. The method will return one of the "enum" values within the following priority. - ValidationEventTypes.Error; - ValidationEventTypes.Warning; - ValidationEventTypes.Info; - ValidationEventTypes.Success;
serverErrors , after sending a message to the server, it is good courtesy to check the validity of the form on the server. As a result, the server may return errors of the final form validation, and the serverErrors array is intended for these very errors. The key feature of serverErrors is automatic clearing of validation messages when the focus is lost from the field, to which server errors were assigned, and server errors are also cleared if the field has been changed.
onChange in addition to the standard "mobx-reaction" mechanism, it is possible to use "delegate" and add a "callback" function to it, which will be called when data changes.
setDirty(dirty: boolean) , the method will allow changing the value of the pristine / dirty fields
setTouched(touched: boolean) the method will allow changing the value of the untouched / touched fields
dispose() is required to call in componentWillUnmount of the control responsible for the page
These were common fields for all controls, but each control also has fields unique to its type. FormControl.
Name Description
value , contains the current value of the field. It is possible to assign a new value to this field either.
FormGroup and FormArray contain
Name Description
wait() the method allows to wait for the end of the check of all (validations), including nested ones
allControls() this method allows to obtain a complete set of all FormControls, including those nested at different levels. That is, it actually expands a multilevel FormGroup object, which may also contain FormGroup, into one large list consisting only of FormControls.
The allControls functionality is required if we want to find the first invalid element and put focus on it. in this case, the code would look like this:
await this.form.wait(); if (this.form.invalid) { this.form.setTouched(true); const firstError = this.form.allControls().find(c => c.invalid && !!c.element); if (!!firstError) { firstError.element.focus(); } } ... 

Validation

Of course, in addition to controls that allow working with data, we will need validations themselves. The package @quantumart/mobx-form-validation-kit typically contains a number of preset validations, as well as supports the creation of own custom validations. Example of setting validations for FormControl for the age field.
new FormControl( this.userInfo.age, [required(), minValue(18, "Вам должно быть больше 18 лет.", ValidationEventTypes.Warning)], v => (this.userInfo.age = v) ) 
Each validation takes as the latest parameters:
Name Description
Message validation message.
eventType message level. 4 message levels are supported.
  • Error
  • Warning
  • Info
  • Success (validity massages). For example, it is possible to verify that the password is really secure.
The package contains the following set of validations:
Name Description
required (... required field
notEmptyOrSpaces (... the field is not empty and does not contain spaces only. It is actually "required", taking into account the prohibition of spaces.
pattern(regExp: RegExp, ... the first parameter is a regular expression that the field should match. An error is generated if there is no pattern matching.
invertPattern(regExp: RegExp, ... , the first parameter is a regular expression that the field should not match. An error is generated if there is pattern matching.
minLength(minlength: number, .... the first parameter is the minimum length of the text, inclusive. An error is generated if the length is less than the transferred one.
maxLength(maxlength: number, .... the first parameter is the maximum length of the text, inclusive. An error is generated if the length exceeds the transferred one.
absoluteLength(length: number, .... the first parameter is the exact length of the text. An error is generated if the length does not match the given one.
minValue(min: TEntity (() => TEntity), ... this validation is intended for numbers and dates only. An error occurs if the value is less than the specified one. The validation feature is the ability to accept not only a specific value as the first parameter, but a function as well. Which means that if the value is being read in this function from the @observable field of the object, the validation itself will be restarted not only when the field requiring validation is changed but also when the "related field" is changed too. Whereupon, no additional manipulations are needed, except to mark the field from which the value is being read as @observable.
maxValue(max: TEntity (() => TEntity), ... this validation is intended for numbers and dates only. An error occurs if the value is longer than the specified one. The validation feature is the ability to accept not only a specific value as the first parameter, but a function as well. Which means that if the value is being read in this function from the @observable field of the object, the validation itself will be restarted not only when the field requiring validation is changed but also when the "related field" is changed too. Whereupon, no additional manipulations are needed, except to mark the field, from which the value is being read as @observable
notContainSpaces (... unlike notEmptyOrSpaces, an error will be generated if the value contains even one space.
compare(expression: (value: TEntity) => boolean (... , writing own validation function generates a lot of copy-paste code; this wrapper has been developed to eliminate this problem. As the first parameter, this validation function accepts a function, to which in turn the current value of the field is transferred. Which allows performing a complex validation. For example, calculating a hash for TIN or passport number. And then return true/false. An error will be displayed if the validation returns false.
isEqual(value: string ... simple string match validation.
The following describes the wrapper functions that serve to control the flow of validation launch. It should be noted that the validation set transferred to FormControl, FormGroup, FormArray is launched in a single array and actually has no execution sequence. As a result of the work, in the errors, warnings, informationMessages, and successes fields, we will obtain arrays consisting of errors, warnings, etc., which are combined into a single array. Often a customer wants to see only one error, but not all at once. Moreover, the ToR may be designed so that one validation is being performed only after the previous one has ended. To solve this problem, the wrapperSequentialCheck wrapper is used. Its call and its application is no different from the usual validator function, but at the input, it receives an array of validators that will be launched sequentially, i.e., the next validation will be launched only after the previous one has ended without errors. The second wrapper function is the control function of the flow of validations. As the first parameter, wrapperActivateValidation takes a function, in which it is required to specify the conditions for activation of validations. Unlike the "activate" function, which is transferred to FormControl, this validation is designed for more complex logic. Let us suppose that we have a common builder for the entire FormGroup form of payments, and moreover, there is only one method on the server that accepts a common set of fields. But the catch is that even though the form is common, we show a different set of fields to the user depending on the "type of payment." Thus, wrapperActivateValidation allows writing a logic, in which various validations will be performed depending on the type of payment. The use of wrappers will look just like the use of ordinary functions.
new FormControl( this.userInfo.megapole, [wrapperActivateValidation(() => this.info.A === 10, [ required(), pattern(/\^d{10}$/) ]), wrapperActivateValidation(() => this.info.A === 20, [ wrapperSequentialCheck([ notContainSpaces(), pattern(/\^d{20}$/) ]) ])], v => (this.userInfo.megapole = v) ) 
This example shows that the required(), pattern(/^d{10}$/) varifications will be performed only at this.info.A === 10, and if this.info.A === 20, the notContainSpaces(), pattern(/^d{20}$/) validations will be triggered; moreover, these validations will be triggered sequentially, unlike the first case.
Of course, the moment will come when the standard set of validations will no longer be enough. Then, it will be required to write own asynchronous functions. Fortunately, this may be done without much difficulty. FormControl was originally designed for asynchronous validation functions, which may want to go to the server for data and it is required to wait such a respond. And as a result, all the validations are asynchronous.
async function checkValueOnServer(control: FormControl): Promise { if (control.value == null) { return []; } const result = await sendToServer(control.value); if (result.errorMessage) { return [ { message: result.errorMessage, type: ValidationEventTypes.Error, }, ]; } return []; 
Here, it is necessary to pay attention to two objects. The first point is the array being returned. So it is actually possible to return several error messages at once, if necessary. The second point is the object being returned; it has the following set of fields.
Name Description
key is an optional field, which allows specifying a "key" for a specific validation. All base fields has a unique "key" which matches their name. A desire may emerge to use "key" to render the list in "react", but as practice has shown, this is a bad idea. Further, I will show in the example that it is better to use "message" and do not touch "key" at all. In any case, it is available, as in Angunar, but the need in it is in fact reduced to null.
message is a validation message. Mandatory field.
type is a type of message. - Error - Warning - Info - Success (validity messages). For example, it is possible to verify that the password is really secure.
additionalData is an additional information that may be transferred along with validation, if necessary. It may be some additional html-markup or a specific style. Generally, anything may be put into "any."

Extensions

Any magic is based on trifles. And in this case, it is required to link FormControl with a specific input field for setting focus, obtaining changes from the fields. Since FormControl does not limit the developer in the type of validated data, it was required to sacrifice a bit of applicability of elements in "react," due to the versatility. At the same time, for "input" and "textarea," it was possible to create simple functions of binding data onto an element; for other components, the processor will still have to make minimal efforts to substitute data.
For "input," the binding element on FormControl (name) will look like this. For "textarea," the binding will be like this



--------------------------------------------
Meeting Calendar -----------------





[xxxxx is sensitive data]
submitted by Harrykeesta to webdevelopment [link] [comments]


2019.08.15 22:33 Harrykeesta Embed form with thank you message and call to schedule apointment

Hi.
I am new to Spacespace and I am not a wizard coder... I am putting together a site for a friend. They'd like to have a contact us form (code from their CRM) that displays a thank you message with a calendar (Code from their appointment manager) to setup a meeting after submission. Below is the code from each platform. On SquareSpace I created a code block and added the first bit of code. I am not sure what to do for the transition from the submission to displaying the thank you / meeting calendar.

Contact form -------------------



* * onkeypress='return event.charCode >= 48 && event.charCode <= 57'
placeholder="E.g.:1234567890" >





--------------------------------------------

Meeting Calendar -----------------






[xxxxx is sensitive data]

-----------------------------------------

Thanks in advance for your help. Have a great day!
submitted by Harrykeesta to squarespace [link] [comments]


2019.03.24 17:36 Tetsuya_the_Wise Need Some help with a project (revised)

Need Some help with a project (revised)
My previous post wasn't very well explained, so i'm making a revised post
___
I'm doing a project for my web development class, and i've run into a problem. I'm trying to make it so a user can edit shipping information here:

https://preview.redd.it/0cd2osg1g3o21.png?width=1433&format=png&auto=webp&s=d19e93ace04c3f11af0f133c37d9428441d5425c
It says "
Notice: Undefined index: Country in /share/35600/35600/Coffman/project1/update.php on line 65
" in the boxes. I'm not sure why it's saying that, because I have that variable in my database. I'll post all the code i'm using for the project below.

(shipping.php) This is the page where users insert shipping information.
"); ?>      Shipping     
Shipping Information
  • " />
  • " />
  • "/>
  • " />
  • " />
  • " />
___
(doShipping) the code that puts the information in the database

 
___
(shippingTableTest) Shows the information the user entered

 >delete
shipping table
Name Address City State Zip Code Country
Information pulled from database
>edit "
___
(update.php) the table for editing shipping information
"); ?>     Edit    

Update

Update Shipping
  • "/>
  • "/>
  • "/>
  • "/>
  • "/>
  • "/>
___
and (doUpdate) the code that's supposed to update the shipping information

 
___
And here's pictures of the data base i'm using


https://preview.redd.it/8r3nt6i1h3o21.png?width=1353&format=png&auto=webp&s=3a3f1f96d7863036021bf3fe04f2366270070f2f

https://preview.redd.it/68lddfx2h3o21.png?width=1614&format=png&auto=webp&s=5f1289774d8e79322c41b8cb6016f04d14708643
I really don't know why it isn't working
submitted by Tetsuya_the_Wise to CodingHelp [link] [comments]


2019.03.22 19:14 Tetsuya_the_Wise Need Some help with a project

Need Some help with a project
I'm doing a project for my web development class, and i've run into a problem. I'm trying to make it so a user can edit shipping information here:

https://preview.redd.it/8gl29ao8mpn21.png?width=1433&format=png&auto=webp&s=97e8c188e0b53bf33d3ae2f53575b5b7c655a5a2
It says "
Notice: Undefined index: Country in /share/35600/35600/Coffman/project1/update.php on line 65
" in the boxes. I'm not sure why it's saying that, because I have that variable in my database. I'll post all the code i'm using for the project below.

(shipping.php) This is the page where users insert shipping information.
session_start();
if(empty($_SESSION["errorMessage"]))
$\_SESSION\["errorMessage"\]=""; 

echo("");
?>



  Shipping  


 

  





Shipping Information

  • " />

  • " />

  • "/>

  • " />

  • " />

  • " />














(doShipping) the code that puts the information in the database
session_start() ;

$Sname = $_POST["Sname"];
$Saddress = ($_POST["Saddress"]);
$Scity = ($_POST["Scity"]);
$Sstate = $_POST["Sstate"];
$Szip = $_POST["Szip"];
$Scountry = $_POST["Scountry"];

if( ($Sname=="") ($Saddress=="") ($Scity=="") ($Sstate=="") ($Szip=="") ($Scountry==""))
{//check for empty form values
$\_SESSION\["errorMessage"\]="You must enter a valid value"; header("Location:shipping.php"); exit; 
}

else
{//its okay
$\_SESSION\["errorMessage."\]=""; 
}

include("includes/openDbConn.php");


//echo $sql;
$result = mysqli_query($db, $sqli);
if(empty($result) )
$num\_results = 0; 
else
$num\_results = mysqli\_num\_rows($result); 

if($num_results != 0)
{
$\_SESSION\["errorMessage"\]="The Shipper ID already exists"; header("Location:shipping.php"); exit; 
}
else
{
$\_SESSION\["errorMessage"\]=""; 
}

$sqli="INSERT INTO shippingP1(name, address, city, state, zip, country) VALUES('".$Sname."','".$Saddress."','".$Scity."','".$Sstate."','".$Szip."','".$Scountry."')";
echo $sqli;
$result = mysqli_query($db, $sqli);

include("includes/closeDbConn.php");

header("Location:shipping.php");
exit;
?>

(shippingTableTest) Shows the information the user entered

include("includes/openDbConn.php");
$sqli = "SELECT name, address, city, state, zip, country FROM shippingP1;" ;
$result = mysqli_query($db, $sqli);
if(empty($result) )
$num\_results = 0; 
else
$num\_results = mysqli\_num\_rows($result); 
?>




 
$row=mysqli_fetch_array($result);

 ?> 
>delete








 
shipping table
Name Address City State Zip Code Country
Information pulled from database

>edit
"




//mysqli\_free\_result($result); include("includes/closeDbConn.php"); 
?>

(update.php) the table for editing shipping information

session_start();

//check for empty session
if(empty($_SESSION["errorMessage"]))
$\_SESSION\["errorMessage"\]=""; 


include("includes/openDbConn.php");

echo("");
?>



 Edit  


Update


include("includes/menu.php"); include("includes/openDbConn.php"); 
?>

$sqli = "SELECT name, address, city, state, zip, country FROM shippingP1";
$result = mysqli_query($db, $sqli);
if(empty($result) )
{
$num\_results = 0; 
}
else
{
$num\_results = mysqli\_num\_rows($result); $row=mysqli\_fetch\_array($result); 
}


?>


Update Shipping

  • "/>

  • "/>

  • "/>

  • "/>

  • "/>

  • "/>







$\_SESSION\["errorMessage"\]=""; include("includes/closeDbConn.php"); 
?>






(doUpdate) the code that's supposed to update the shipping information
session_start() ;

include("includes/openDbConn.php");

$Sname = $_POST["Sname"];
$Saddress = ($_POST["Saddress"]);
$Scity = ($_POST["Scity"]);
$Sstate = $_POST["Sstate"];
$Szip = $_POST["Szip"];
$Scountry = $_POST["Scountry"];

if( empty($shipperID) )
{
header("Location:shipping.php"); exit; 
}

$sql = "UPDATE shippingP1 SET name='".$Sname."', address='".$Saddress."', city='".$Scity."' , state='".$Sstate."' , zip='".$Szip."' , country='".$Scountry."'";
//echo $sql;

$result = mysqli_query($db,$sql);
include("includes/closeDbConn.php");

header("Location:shipping.php");

?>

And here's pictures of the data base i'm using

https://preview.redd.it/5vmfpjwropn21.png?width=1353&format=png&auto=webp&s=4897354e54ac968dfd201f78f4c0c40d95daaa1b

https://preview.redd.it/otn8htotopn21.png?width=1614&format=png&auto=webp&s=3fa3005acacc5cc31adcee0f1a26ec86409857c5
I really don't know why it isn't working.
submitted by Tetsuya_the_Wise to CodingHelp [link] [comments]


2019.02.01 06:09 smoledman maxLength validator not working completely

a portion of template:
 
Required Cannot exceed 400 characters
The component code:
 this.abstract = new FormControl('', [Validators.required, Validators.maxLength(400)]); 
The thing is the enclosing
properly shows the error styling and the first is hidden when I put in > 400 characters, so abstract.invalid is true. But somehow the condition for maxLength is not evaluating to true and the 2nd is removed.
submitted by smoledman to Angular2 [link] [comments]


2018.10.12 16:52 brilliantmojo How do I give an unchecked check box a string so the user sees my $error_message if it is unchecked?

HTML






PHP (send_form_email.php)

"; echo "Please fix these errors."; die(); } // validation expected data exists if( !isset($_POST['name']) !isset($_POST['email']) !isset($_POST['company']) !isset($_POST['telephone']) !isset($_POST['comments']) !isset($_POST['GDRP']) ) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $name = $_POST['name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $company = $_POST['company']; // not required $comments = $_POST['comments']; // required $GDRP = $_POST['GDRP']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$name)) { $error_message .= '

Full Name

'; } if(!preg_match($email_exp,$email_from)) { $error_message .= 'Email Address

'; } if(strlen($comments) < 2) { $error_message .= 'Comments

'; } if(empty($GDRP)) { $error_message .= 'GDRP Agreement

'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name: ".clean_string($name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Company: ".clean_string($company)."\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> Thank you for contacting us. We will be in touch with you as soon as possible.
My $GDRP's $error_message isn't showing when the checkbox is unchecked. I learned that the browser doesn't give a value to unchecked check boxes. I've seen this be used before though, do any of you know a work around so the user gets $error_message when the form is submitted without checking GDRP
submitted by brilliantmojo to PHPhelp [link] [comments]


2018.10.09 19:37 brilliantmojo Checkbox not showing $error_message when unchecked

HTML
























I consent to having this website store my submitted information so they can respond to my inquiry.












_____________________________________________




PHP


if(isset($_POST['email'])) {
$email_to = ["[email protected]](mailto:"[email protected])";
$email_subject = "www.Adress.com - CONTACT FORM";
function died($error) {
// error code goes here
echo "We are very sorry, but there were error(s) found with the form you submitted: ";
echo $error."
";

echo "Please fix these errors.";
die();

}
// validation expected data exists
if(

!isset($_POST['name'])
!isset($_POST['email'])
!isset($_POST['company'])
!isset($_POST['telephone'])
!isset($_POST['comments'])
!isset($_POST['GDRP'])

) {

died('We are sorry, but there appears to be a problem with the form you submitted.');

}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$company = $_POST['company']; // not required
$comments = $_POST['comments']; // required
$GDRP = $_POST['GDRP']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$name)) {
$error_message .= '

Full Name

';

}

if(!preg_match($email_exp,$email_from)) {
$error_message .= 'Email Address

';

}

if(strlen($comments) < 2) {
$error_message .= 'Comments

';

}

if(empty($GDRP)) {
$error_message .= 'GDRP Agreement

';

}

if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Company: ".clean_string($company)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

?>


Thank you for contacting us. We will be in touch with you as soon as possible.


}
?>
If I check the checkbox and fill all the required fields I don't get an error and it sends as expected. But if I don't check the checkbox I don't get any $error_message (even if I don't fill any of the required fields). I've been trying to figure this out for 2 days and still got nothing.
submitted by brilliantmojo to PHPhelp [link] [comments]


2018.09.01 11:16 Elniche37 Html and JavaScript

Greeting world, I am attempting to output a user's name following a salutation in my alert box. I created a label tag and gave it a class. In this label tag the user can input there name. I targeted the class in JavaScript but it returns as undefined. THIS IS MY HTML CODE:
























This is my JAVASCRIPT Code:

function ValidateEmail(Emailid) {
if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(blanca.Emailid.value)) {
var Barbara = document.getElementsByClassName("lion").value; I TARGET THE LION
CLASS HERE SO I CAN STORE THE USER'S NAME IN THE BARBARA VARIABLE...
I CALL ON THE VARIABLE IN THE ALERT ELEMENT BUT IT RETURNS UNDEFINED.
alert("Thank You," + Barbara + " " + "I will respond within 24-48 hours!"*/);
}
else {
alert("Invalid Email Address!");
}
}
submitted by Elniche37 to AskProgramming [link] [comments]


2018.05.03 23:24 codehope801 Contact Form -- where is the ACTION?

I have a contact form that is part of a template but it is lacking an 'action' attribute for the form element. How in the heck does this form actually send out the email?
Fields marked with a *are required.
submitted by codehope801 to HTML [link] [comments]


2017.06.09 14:36 Reelix ASP.NET - How to get Visual Studio to keep MaxLength on MultiLine TextBox?

I'm currently running Visual Studio Professional 2015 (Update 3), and if I create a Textbox, set TextMode to MultiLine, and MaxLength to 50, the rendered Textarea will remove the MaxLength tag.
I can only assume that this is because the MaxLength tag was not valid in HTML4. However, with the introduction of HTML5, it is now supported by all modern browsers, so I would prefer not to resort to Javascript keypress event hackery :) Our site currently blocks login if you're not running at least IE10, so I can guarantee that this event will work with the users browser.
So - How do I get Visual Studio to not remove the now-valid tag? Does it still do this in 2017? I suppose I could post-add the tag to the element through C#, but if it didn't remove it in the first place - That'd be ideal :)
I am currently limited to 2015 due to my work environment.
submitted by Reelix to dotnet [link] [comments]


2017.05.08 19:16 whiztler Help with form submitting

Newbie here. I am trying to apply some visual process information when a user clicks on the form submit button.
Not all the code is executed (not error is given). Why is not the entire script executed. It seems to halt after $(".rfq-success-message").slideDown(500);
Here's the code:
// Init $(document).ready(function () { $(".rfq-success-message").hide(); $(".rfq-error-message").hide(); $(".rfq-submit-spinner").hide(); $('textarea').maxlength({ alwaysShow: true }); $('.conditional').conditionize(); $('#rfq').validator().on('submit', function (e){ if (e.isDefaultPrevented()) { // handle the invalid form... // formError(); } else { e.preventDefault(); $('#submit-btn').attr("disabled",true); $(".rfq-submit-icon").hide(); $(".rfq-submit-spinner").show(); $('#submit-btn span').html(submitLoadText); submitForm(); } }); if ($("#form_language").val() == 'en'){ var submitLoadText = "Sending, please wait..."; var submitIdleText = "Send Request for Quotation"; } else { var submitLoadText = "Enviando, por favor espere..."; var submitIdleText = "Enviar la solicitud de presupuesto"; }; }); function formSuccess(){ $(".rfq-success-message").slideDown(500); $(".rfq-submit-spinner").hide(); $(".rfq-submit-icon").show(); $('#submit-btn span').html(submitIdleText); $("#rfq")[0].reset(); $('#submit-btn').attr("disabled",false); }; function formError(){ $(".rfq-error-message").slideDown(500); $("#submit-btn").slideUp(300); }; function submitForm(){ var productID = $("#productID").val(); var form_language = $("#form_language").val(); // etc. $.ajax({ type: "POST", url: "../../inc/OC_proc-rfq.php", data: "productID=" + productID + "&form_language=" + form_language + "&prefix_name=" + // etc success : function(text){ if (text == "success"){ formSuccess(); } else { formError(); } } }); }; 
submitted by whiztler to jquery [link] [comments]


2017.02.08 20:46 tangerto Can somebody help me out with my Angular PHP mailer contact form?

It's not working right now. I'm getting a "Syntax error: Unexpected token ":". Parse error"
Markup:
 

Hungry?





Controller:
function FormController($http) { var vm = this; vm.formData = {}; vm.processForm = function() { $http({ method: 'POST', url: '/php/mail.php', data: $.param(vm.formData), dataType: "json", headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(function (data) { console.log(data); if (!data.success) { //binding errors to data. vm.error_first_name = data.errors.first_name; vm.error_last_name = data.errors.last_name; vm.error_email = data.errors.email; vm.error_message = data.errors.message; console.log(data.errors.first_name); console.log(data.errors.last_name); console.log(data.errors.email); console.log(data.errors.message); } else { // if successful, bind success message to message console.log("We got it"); console.log(vm.formData); vm.formData.first_name = ""; vm.formData.last_name = ""; vm.formData.email = ""; vm.formData.message = data.message; } }); }; 
mail.php:
require 'PHPMailerAutoload.php'; require 'class.phpmailer.php'; require 'class.smtp.php';
$errors = array(); // array to hold validation errors $data = array(); // array to pass back data
// validate the variables ====================================================== if (empty($_POST['first_name'])) $errors['first_name'] = 'First name is required.'; if (empty($_POST['last_name'])) $errors['last_name'] = 'Last name is required.'; if (empty($_POST['email'])) $errors['email'] = 'Email is required.'; if (empty($_POST['message'])) $errors['message'] = 'Message is required.';
// return a response ===========================================================
// response if there are errors if (!empty($errors)) { // if there are items in our errors array, return those errors $data['success'] = false; $data['errors'] = $errors; } else { $mail = new PHPMailer(); // create a new object $mail->SMTPAuth = true; // authentication enabled $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail $mail->Host = "smtp.gmail.com"; $mail->Port = 587; $mail->IsHTML(true); $mail->Username = "MYEMAIL"; //Email that you setup $mail->Password = "MYPASS"; // Password $mail->Subject = "Mail from " . $_POST['last_name'] . ", e-mail: " .$_POST['email']. ""; $mail->Body = $_POST['message']; $mail->AddAddress("MYEMAIL"); //Pass the e-mail that you setup if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { $data['success'] = true; } } 
echo json_encode($data);
?>
submitted by tangerto to angularjs [link] [comments]


2017.01.24 23:09 tangerto More noob trouble with PHPMailer: "Cannot POST /php/mail.php" in AngularJS.

So I have a simple Angular app I'm building with a contact form. I'm running the site locally on my machine and every time I try to submit my mail form, I get the error "Cannot POST /php/mail.php".
Some code:
Markup:
  

Hungry?





Angular function for processing mail
function FormController($http) { var vm = this; vm.formData = {}; vm.processForm = function() { $http({ method: 'POST', url: '../php/mail.php', data: $.param(vm.formData), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .success(function (data) { console.log(data); if (!data.success) { console.log(data); } else { vm.message = data.message; } }); }; } 
PHP script
IsSMTP(); // enable SMTP $mail->SMTPAuth = true; // authentication enabled $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail $mail->Host = "smtp.gmail.com"; $mail->Port = 465; // or 587 $mail->IsHTML(true); $mail->Username = "MYEMAIL"; //Email that you setup $mail->Password = "MYPASSWORD"; // Password $mail->Subject = "Mail from " . $_POST['last_name'] . ", e-mail: " .$_POST['email']. ""; $mail->Body = $_POST['message']; $mail->AddAddress(""); //Pass the e-mail that you setup if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { $data['success'] = true; $data['message'] = 'Thank you for sending e-mail.'; } } echo json_encode($data); ?> 
submitted by tangerto to PHP [link] [comments]


2016.04.27 05:45 lol2dubs PHP background not working

I'm using a PHP page I found on the web to build a registration and login system for my page. It works well, and I can manipulate it as I want for the most part.
Then I got the idea that rather than it just be a white page, it'd be cool to have a random image display behind the login/registration box. So I looked up some code and found another script on css-tricks to randomize the background image on each load from the images/backgrounds folder. I've changed all the script around the way it should be, and it works when I'm in MY website (the HTML/CSS that I've built for my home page) but it doesn't work when I plug it in to the login.php page from the login package I found on the web.
Can you guys look at this and see if you can figure out why it won't display this image?
Login()) { $fgmembersite->RedirectToURL("login-home.php"); } } ?>     Login       
Login
* required fields
GetErrorMessage(); ?>
' maxlength="50" />
CSS
/* Registration/Login Form by html-form-guide.com You can customize all the aspects of the form in this style sheet */ #fg_membersite { margin-left: 40%; margin-top: 5%; } #fg_membersite fieldset { width: 230px; padding:20px; border:1px solid #ccc; -moz-border-radius: 10px; -webkit-border-radius: 10px; -khtml-border-radius: 10px; border-radius: 10px; } #fg_membersite legend, #fg_membersite h2 { font-family : Arial, sans-serif; font-size: 1.3em; font-weight:bold; color:#333; } #fg_membersite label { font-family : Arial, sans-serif; font-size:0.8em; font-weight: bold; } #fg_membersite input[type="text"],#fg_membersite textarea, #fg_membersite input[type="password"] { font-family : Arial, Verdana, sans-serif; font-size: 0.8em; line-height:140%; color : #000; padding : 3px; border : 1px solid #999; -moz-border-radius: 5px; -webkit-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px; } #fg_membersite input[type="text"], #fg_membersite input[type="password"] { height:18px; width:220px; } #fg_membersite #scaptcha { width:60px; height:18px; } #fg_membersite input[type="submit"] { width:100px; height:30px; padding-left:0px; } #fg_membersite textarea { height:120px; width:310px; } #fg_membersite input[type="text"]:focus, #fg_membersite textarea:focus { color : #009; border : 1px solid #990000; background-color : #ffff99; font-weight:bold; } #fg_membersite .container { margin-top:8px; margin-bottom: 10px; } #fg_membersite .error { font-family: Verdana, Arial, sans-serif; font-size: 0.7em; color: #900; background-color : #ffff00; } #fg_membersite #register_password_errorloc { clear:both; } #fg_membersite fieldset#antispam { padding:2px; border-top:1px solid #EEE; border-left:0; border-right:0; border-bottom:0; width:350px; } #fg_membersite fieldset#antispam legend { font-family : Arial, sans-serif; font-size: 0.8em; font-weight:bold; color:#333; } #fg_membersite .short_explanation { font-family : Arial, sans-serif; font-size: 0.6em; color:#333; } /* spam_trap: This input is hidden. This is here to trick the spam bots*/ #fg_membersite .spmhidip { display:none; width:10px; height:3px; } #fg_membersite #fg_crdiv { font-family : Arial, sans-serif; font-size: 0.3em; opacity: .2; -moz-opacity: .2; filter: alpha(opacity=20); } #fg_membersite #fg_crdiv p { display:none; } #fg_membersite_content li { font-family : Arial, sans-serif; padding-top:10px; padding-bottom:10px; } #fg_membersite_content { font-family : Arial, sans-serif; font-size: 0.9em; line-height: 150% } #fg_membersite_content h2 { font-family : Arial, sans-serif; font-size: 1.5em; font-weight:bold; color:#333; } 
Specifically, this part should set the random background. My images are named correctly, etc.
 html { height: 100%; width: 100%; background-repeat: no-repeat; background-attachment: fixed; background-size: 100% 100%; background-position: right top; background-image: url('\images\backgrounds\1.jpg'); /* replace 10 by the number of backgrounds you have in images/backround/ and named bg-x.png */ } 
Thanks.
submitted by lol2dubs to PHPhelp [link] [comments]


2015.05.30 00:28 yiggins Contact Form Hidden text area help

new to here so hello to you all. i have a contact form online that i keep getting spammed to death by bots, so i have been reading about hidden text boxes that bots fill in but the form wont send. i would like for your comments on if the following code in both PHP and the HTML form are correct to stop this. thank you in advance for your comments. HTML form:-
 

CONTACT US
Using The Form Below Will Contact Us Directly



Your email address will never be published or shared.






This is the PHP script:-
 
submitted by yiggins to PHPhelp [link] [comments]


2014.10.25 00:38 Jormadjesty Help with my PHP contact form

My php form is not working trying to figure out why here is my html

Contact Us




  



and here is my PHP
Untitled Document
if(isset($_POST['email'])) {
$email_to = "@domain.com"; $email_subject = " new message"; function died($error) { echo "We are very sorry, but there were error(s) found with the form you submitted. "; die(); } if(!isset($_POST['subject']) !isset($_POST['your_name']) !isset($_POST['TELEPHONE']) !isset($_POST['EMAIL']) !isset($_POST['message'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $SUBJECT = $_POST['subject']; // required $last_name = $_POST['your_name']; // required $EMAIL_from = $_POST['EMAIL']; // required $telephone = $_POST['TELEPHONE']; // not required $message = $_POST['message']; // required $error_message = ""; $EMAIL_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; 
if(!preg_match($EMAIL_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}
$string_exp = "/^[A-Za-z .'-]+$/"; 
if(!preg_match($string_exp,$your_name)) {
$error_message .= 'The name you entered does not appear to be valid.
';
}
if(strlen($comments) < 2) {
$error_message .= 'The message you entered do not appear to be valid.
';
}
if(strlen($error_message) > 0) {
died($error_message); 
}
$email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Your Name: ".clean_string($your_name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n"; $email_message .= "Message: ".clean_string($message)."\n"; 
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.
'; } else { echo 'Something went wrong, go back and try again!
'; } }
?>
Any help is greatly appreciated
submitted by Jormadjesty to PHPhelp [link] [comments]