ReactJS - Front-end form error handler/validation - reactjs

I'm building a simple donation app in ReactJS. Here is a working version here:
https://stackblitz.com/edit/react-grzdgz
I've never done form error validation though. So if someone doesn't fill out a field, I'd like an error message to pop up, which says something like "this field must be completed".
I've been trying to follow this tutorial:
https://learnetto.com/blog/how-to-do-simple-form-validation-in-reactjs
But I'm kinda getting lost, about how I can pass these functions/error messages, into my form, which sits in a seperate module. In the demo, everything sits in one file.
But in my app, my form sits seperately to index.js. So I link to it in index.js.
I'm almost there, I just need some help connecting everything up.
Can anyone help me get form error validation working?
The error handling functions all sit here:
https://stackblitz.com/edit/react-grzdgz
The form itself sits here:
https://stackblitz.com/edit/react-grzdgz?file=components%2FForm.js
And some form errror heres:
https://stackblitz.com/edit/react-grzdgz?file=components%2FFormErrors.js
Any help would be great!
Thank you!

On the submit, I would have a method called: validateFields, which would validate all field like you want (instead of using the default validator of html, which doesn't work on some browser). In the method, I would save all the field with an error.
If the error list (or object) is not empty, you use an alert or popup react-popup
If there are no error, you can call submit method.
Basically, it would look something like:
export default class DumbComponent extends React.Component {
state = {} // all your field value
validateField = () => {
let error = []
//Validate all your field
if (error.length === 0) {
this.submit()
} else {
this.showError() // You decide the way
}
}
render() {
return (
<Form>
<FieldOne />
<Field2 />
<SubmitButton onSubmit={this.validateField} />
</Form>
)
}
}
Hope it answer your question!

Related

Build optionally layouts in NextJS by detecting the browser URL value

all I would try to make some optional layout in NextJS. My problem is that I have found some method to check the browser URL then serve content according to these URL. But by this way the server content an browser content are no longer identical, hence the schema breaks.
Here an snippet of my trial:
export default ({children, title = 'title' }) => {
var
contact = false;
if (exenv.canUseDOM ){ if (window.location.href==="http://localhost:4000/contact" ) { contact= true}; }
else {const contact = false};
if (contact){ return( <div>Hey it is contact ! </div> ) }
else { // return normal layout
My console returns me predictably:
Warning: Text content did not match. Server:
So... I'm wondering if I have to make some custom settings on a custom NextJS server to grant the backend/frontend behaviors?
Or maybe there is a less expensive solution in the area?
Any hint would be great,
thanks
You can't remove that warning, it is appear because you just render that layout from client side, so there is a different between layout rendered by server and layout rendered by client.
I don't know what variable exenv.canUseDOM is, but you can use process.browser to detect if the current process is server side rendering or not.

How to use React with PowerBI custom visual

I'm trying to progress a Power BI Custom Visual react sample to the stage where it can access the dataViews of the parent visual in the React component.
The sample in question is https://github.com/ignatvilesov/powerbi-visuals-react-sample
Answers to this question may not require expertise in Power BI custom visuals, knowledge of React may be sufficient.
In the Update method of the visual it create the calls ReactDOM.render like this: ReactDOM.render(React.createElement(App), this.element);
This works and creates a component that allows the react component to display elements in the visual.
When I attempt to pass the data options: VisualUpdateOptions like this: ReactDOM.render(React.createElement(App,{options} ), this.element); , I am finding problems.
I don't understand how to get the options object using props, I've tried a variety of things, here is a sample of my attempts at an App.tsx
module powerbi.extensibility.visual {
export class App extends React.Component<any,any> {
constructor(props: VisualUpdateOptions) {
super(props);
}
public render() {
var message = "";
if (this.props == null){
message = "no data"
}
else
{
message = "got data"
}
var message2 = "";
if (this.props.dataViews == null)
{
message2 = "no dataview"
}
else
{
message2 = "got dataview"
}
...
I get data ok, message2 always gives me no dataview.Any advice would be greatly appreciated, I have great ignorance in this area and seek enlightenment :-)
I think you should try to pass the props object to create element inside the visual.ts (where you create an instance of the react app). Something like this:
ReactDOM.render(React.createElement(App, {"yourProp": "props"}), this.element);
Console log the props as you are doing now, you should see them.

Custom changes in Sonata Admin PreUpdate prevent persiting of object

I am using Doctrine 2.4.8 in my Symfony 2.8.34 project.
My Problem is that custom changes I made in the preUpdate function preventing the expected changes from the admin form. Dependent on a choice field a new event should been created or deleted.
class CustomAdmin extends AbstractAdmin {
public function preUpdate($object) {
...
if ($object->isDetached()) {
$event = new Event();
...
$object->setDetachedEvent($event);
} else {
$object->setDetachedEvent(null);
}
}
}
Now, the line $object->setDetachedEvent(null); turns everything crazy. The first time I'm saving the form my custom changes in that preUpdate function are executed, but the changes in the fields of the admin form are ignored. The second time the changes from the admin form were executed. If I remove the line above, everythings works fine.
So, anybody has an idea how to handle this problem?

Opencart 2.0.3.1 - contact form not validating

I am using the default Opencart 2.0.3.1. Everything works great, except for the contact form. For some reason, it does not validate the form, and gives no errors after submitting. Any ideas? You can view it here: https://sgroiinnovations.com/index.php?route=information/contact
I can not figure it out. The same type of validation is used for entering a review, and it works correctly. In the contact form, when submit is clicked, it submits the form with no information entered. No errors are provided before or after the page is submitted.
In the contact.php, there is no question that it is calling the validate function below, but again for some reason, the submit button just seems to submit the page (form) without this process.
I'm guessing there is something simple that I am missing, but I can't catch it. Any help would be appreciated. Thx
protected function validate() {
if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 32)) {
$this->error['name'] = $this->language->get('error_name');
}
if (!preg_match('/^[^\#]+#.*.[a-z]{2,15}$/i', $this->request->post['email'])) {
$this->error['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['enquiry']) < 10) || (utf8_strlen($this->request->post['enquiry']) > 3000)) {
$this->error['enquiry'] = $this->language->get('error_enquiry');
}
if ($this->config->get('config_google_captcha_status')) {
$recaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($this->config->get('config_google_captcha_secret')) . '&response=' . $this->request->post['g-recaptcha-response'] . '&remoteip=' . $this->request->server['REMOTE_ADDR']);
$recaptcha = json_decode($recaptcha, true);
if (!$recaptcha['success']) {
$this->error['captcha'] = $this->language->get('error_captcha');
}
}
return !$this->error;
}
Problem fixed. The issue was that I was forwarding http to https using .htaccess. This blew up the contact form because of non-secure to secure. Not sure why, but I removed the redirect and it works.

Bootstrap Validation Manipulation AngularJS

I have an input box for a new user to put in a userid. I want to dynamically check if the userid is already taken on-blur. I'm using bootstrap validation for form validation, and I'm having a hard time figuring out how to make it do what I want. In the validation, I have this code currently for userid:
userid: {
container: '#useridMessage',
validators: {
notEmpty: {
message: '*Required'
},
stringLength: {
min:3,
message: 'Username must be at least 3 characters long'
}
}
},
What I want to be able to do in there is call a function I have for the on-blur action:
$scope.userCheck = function () {
userAPIService.getUserDetails($scope.user.username).success( function ( data ) {
if(data.Status == 0){
//make box red and invalid
}
}).error( function ( error ) {
$scope.status = "Error is checking Username availability";
})
}
My backend function is the getUserDetails which is a GET function. I was planning on, as is shown in the code, to check if the userid is a valid one (data.status == 0) already in our system and notify the user after that it is already taken. My desire is to maintain good coding practice and not by pass my bootstrap validation ( which is working well for everything else ) and make both work together, but since bootstrap validation is kind of a black box, I'm not sure how to do this.
Question: How can I get the validation to check some boolean variable, or how can I get the validation to make the backend call and then analyze the result like I want?
Thoughts:
Ideally I'd like to be able to call the onblur function which would set some boolean and then the validation would just look at the validation, but I'm open to any idea to get this right. Thanks
I wonder if creating a custom validation directive would be a good approach. There's a good overview here How to add custom validation to an angular js form, also in the Custom Validation section of the Angular JS Forms documentation. Hope this helps.

Resources